I am trying to remove an object from an existing JArray
, but when I run the method to delete the property from the JArray
, the property still exists.
I tried simply using the code below
JObject rss1 = JObject.Parse(File.ReadAllText("online.json"));
JObject uList = (JObject)rss1["uList"];
JArray newOnline = (JArray)uList["online"];
newOnline.Remove("value");
The code above is almost directly copied and pasted from the Newtonsoft.Json documentation on modifying Json, but only changed to remove the new item instead of adding it. I've tried other post's solutions, but none of them work. Adding the field works as expected, but trying to remove it does not work whatsoever.
Below is the JSON file's contents
{
"uList": {
"placeHolder": "placeHolderValue",
"online": [
"value"
]
}
}
Below is the expected JSON output of the code being ran
{
"uList": {
"placeHolder": "placeHolderValue",
"online": [
]
}
}
And, below, is the actual output of the code being ran
{
"uList": {
"placeHolder": "placeHolderValue",
"online": [
"value"
]
}
}
Am I doing something wrong and not realizing it?
CodePudding user response:
The problem you've got is that you don't actually have a string
in your array, you have a JValue
. The JArray.Remove
method accepts a JToken
, but the JToken
produced by implicitly casing your string to a JValue
is not equal to the one being removed.
There's one of two solutions that come to mind:
- Find the item in the array and then pass that to the remove method:
JToken item = newOnline.FirstOrDefault(arr => arr.Type == JTokenType.String && arr.Value<string>() == "value");
newOnline.Remove(item);
- Use the
.Remove
method of the array item to remove it from the array:
JToken item = newOnline.FirstOrDefault(arr => arr.Type == JTokenType.String && arr.Value<string>() == "value");
item?.Remove();
CodePudding user response:
You can also remove JToken by querying value
string present in online
JArray.
Parse string to JObject:
JObject rss1 = JObject.Parse(File.ReadAllText("online.json"));
Now remove particular token using below query.
rss1.SelectTokens("$.uList.online[?(@ == 'value')]").FirstOrDefault()?.Remove();