user299967 user299967 - 3 days ago 5
C# Question

Adding JSON property using Newtonsoft.Json

I have some JSON that looks like this:

{
"staticInfo": {
"browser": "Chrome",
"browserVersion": "54.0",
"packageNumber": "XXX",
"user": "user"
}
,
"request": {
"server": "E",
"steps": {
"Step1": {
"start": "11/30/2016 20:11:26.494",
"end": "11/30/2016 20:11:26.510"
}
,
"Step2": {
"start": 1480536689237,
"end": 1480536689357
}
,
"Step3": {
"start": "Wed, 11/30/2016 20:12:25.229 GMT",
"end": "Wed, 11/30/2016 20:12:25.246 GMT"
}
}
,
"url": "SomeURL",
"trackingId": "99809eb5-c36b-4199-83d6-847c7b0489d1:0"
}
}


I am trying to add a Step4 so the final JSON looks like this

{
"staticInfo": {
"browser": "Chrome",
"browserVersion": "54.0",
"packageNumber": "XXX",
"user": "user"
}
,
"request": {
"server": "E",
"steps": {
"Step1": {
"start": "11/30/2016 20:11:26.494",
"end": "11/30/2016 20:11:26.510"
}
,
"Step2": {
"start": 1480536689237,
"end": 1480536689357
}
,
"Step3": {
"start": "Wed, 11/30/2016 20:12:25.229 GMT",
"end": "Wed, 11/30/2016 20:12:25.246 GMT"
}
,
"Step4": {
"start": "SomeData",
"end": "SomeData"
}

}
,
"url": "SomeURL",
"trackingId": "99809eb5-c36b-4199-83d6-847c7b0489d1:0"
}
}


So basically I am trying to add a
Step4
. I am trying to accomplish this using
Newtonsoft.Json
. I know that I can do it using basic string parsing but just for consistency I would like to use the
Newtonsoft.Json
class.

L.B L.B
Answer

Since JObject also implements IDictionary, You can do:

var jObj = JObject.Parse(json);
jObj["request"]["steps"]["Step4"] = JToken.FromObject(new { start = "some", end = "somedata" });
var newjson = jObj.ToString( Newtonsoft.Json.Formatting.Indented);

OR using dynamic keyword

dynamic jObj = JObject.Parse(json);
jObj.request.steps.Step4 = JToken.FromObject(new { start = "some", end = "somedata" });
var newjson = jObj.ToString( Newtonsoft.Json.Formatting.Indented);
Comments