Reputation: 159
I have the following JSON file (list.json):
[
{
"groupID": "12345",
"subID": "71",
"stock": false,
"price": "32.21"
},
{
"groupID": "12345",
"subID": "25",
"stock": false,
"price": "12.94"
}
]
What a I like to do is, that I edit the "stock" value of one specific object. So if the value of stock is false I like to change it to true and if its true I like to change to false.
I tried to start but I have already at the beginning a big problem. I get already while the parsing a Newtonsoft.Json.JsonReaderException : 'Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.'. I believe it happens because the JSON starts with an array.
My method:
public void EditJSON (string GroupID, string SubID)
{
JObject JSONnew = JObject.Parse(list.json);
if (*stock is true*)
{
*change stock to false*
}
if (*stock is false*)
{
*change stock to ture*
}
}
How I can find in the JSON the correct object by using the GroupID and the SubID and edit the value of stock from false to true or the opposit?
Upvotes: 2
Views: 662
Reputation: 23228
You should parse your JSON to JArray
, then filter items by groupID
and subID
values. Finally enumerate the filtered items one by one and change a stock
value, if needed
var items = JArray.Parse(jsonString);
var filtered = items.Where(i => i["groupID"]?.Value<int>() == 12345 && i["subID"]?.Value<int>() == 25);
foreach (var item in filtered)
{
var stock = item["stock"]?.Value<bool>();
if (stock == null)
continue;
if (stock.Value)
item["stock"] = false;
else
item["stock"] = true;
}
Console.WriteLine(items);
Upvotes: 0
Reputation: 69
Try this.
var json = "[{\"groupID\":\"12345\",\"subID\":\"71\",\"stock\":false,\"price\":\"32.21\"},{\"groupID\":\"12345\",\"subID\":\"25\",\"stock\":false,\"price\":\"12.94\"}]";
var data = JsonConvert.DeserializeObject<List<StockData>>(json);
foreach (var item in data.Where(d => d.Stock == false))
{
item.Stock = true;
}
Where the StockData class will be:
public class StockData
{
public string GroupID { get; set; }
public string SubID { get; set; }
public bool Stock { get; set; }
public string Price { get; set; }
}
Good luck!
Upvotes: 1