Xaphann Xaphann - 3 months ago 22
C# Question

JSON update/replace node via LINQ

I need to take a

JSON
file and update/replace some objects of the
JSON
file. The problem is when I split the
JSON
into different
JObject
they are always
null
.

background:
I need to parse and update a
JSON
file with multiple objects based on
ObservableCollection
(can assume that class of the ObservableCollection will match perfectly the object in the JSON file). Here is a sample of the JSON

{
"Customers": [
{
"FirstName": "Bob",
"LastName": "Smith"
},
{
"FirstName": "Jane",
"LastName": "Doe"
}
],
"Subs":[
{
"SubID": "100",
"Descript": "Sub 1"
},
{
"SubID": "200",
"Descript": "Sub 2"
}
]
}


In my WPF application, there will be an
ObservableCollection
for
Customers
and
Subs
. So I figured that I could take the entire
JSON
, parse out the object that I need, do the updating, then updates the object to save the changes in the
JSON
like this;

JObject mainJson = JObject.Parse(File.ReadAllText("MyJSON.json"));
JObject cust = (JObject)mainJson["Customers"];
myColllection = JsonConvert.DeserializeObject<ObservableCollection<Customers>>(cust.ToString());
///Do update logic
cust = JObject.Parse(JsonConvert.SerializeObject(myColllection));
File.WriteAllText("MyJSON.json", mainJson.ToString());


Problem is that cust is always null. I cannot figure out what am I am doing wrong. Also, should I be doing this some other way?

L.B L.B
Answer

The problem with your code is that mainJson["Customers"] is an array not a JObject. Change your code as

JArray cust = (JArray)mainJson["Customers"];