Newtonsoft json help - remove a value
Suppose I have the following json string:
Code:
{
"settings": {
"setting1": "someString",
"setting2": 10,
"setting3": 20,
},
"favorites": [
"thisOne",
"thatOne", <--- remove this line
"theOtherOne"
],
"history": [
{
"param1": "someVale",
"param2": "someValue",
"param3": "someValue",
},
{
"param1": "someVale",
"param2": "someValue",
"param3": "someValue",
}
]
}
How can I remove one item from the "favorites" node by its value? So for example, if I wanted to remove "thatOne" from the json string above, how would I do that? I've looked through the documentation but couldn't find anything to help. Thanks...
Re: Newtonsoft json help - remove a value
Deserialize to object with List(Of Favorite) inside, remove from list the desired item, serialize to JSON
Re: Newtonsoft json help - remove a value
Quote:
Originally Posted by
peterst
Deserialize to object with List(Of Favorite) inside, remove from list the desired item, serialize to JSON
Thanks for the reply. I tried your suggestion & came up with the following bit of code, but it's not working for me..
Code:
Dim jsonObject As JObject = JObject.Parse(IO.File.ReadAllText(myFilename))
Dim fToken As JToken = jsonObject.SelectToken("favorites")
Dim fItems As JArray = CType(fToken, JArray)
Dim fList As List(Of String) = JsonConvert.DeserializeObject(Of List(Of String))(fItems)
What am I doing wrong? Can you give me a quick example of the correct way? This is my first time using the Newtonsoft library & I'm still trying to learn how to use it. Thanks...
Re: Newtonsoft json help - remove a value
Deserialize the whole JSON to object (e.g. named MasterSettings) that contains Favorites as List(Of Favorite) or just list of strings as in your example. Then use the root object to reach the favorites and remove item: MasterSettings.Favorites.RemoveAt(...)
VB.NET pseudo code Code:
Dim settings = JsonConvert.DeserializeObject(Of MasterSettings)(json)
settings.Favorites.RemoveAt(1)
Dim newJson = JsonConvert.Serialize(settings)
Re: Newtonsoft json help - remove a value
I can't use .RemoveAt() because I wont know the index. That's why I asked how to remove by specifying the actual value...
Re: Newtonsoft json help - remove a value
It is list, just do whatever you will do with list to find a value. Last hint: LINQ