我有一些看起来像这样的JSON:
{
"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"
}
}
我正在尝试添加Step4,因此最终的JSON看起来像这样
{
"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"
}
}
所以基本上我正在尝试添加Step4
。我正在尝试使用Newtonsoft.Json
来完成此任务。我知道我可以使用基本的字符串解析来完成它,但为了保持一致性,我想使用Newtonsoft.Json
类。
答案 0 :(得分:4)
由于JObject
也实现了IDictionary
,您可以执行以下操作:
var jObj = JObject.Parse(json);
jObj["request"]["steps"]["Step4"] = JToken.FromObject(new { start = "some", end = "somedata" });
var newjson = jObj.ToString( Newtonsoft.Json.Formatting.Indented);
或使用dynamic
关键字
dynamic jObj = JObject.Parse(json);
jObj.request.steps.Step4 = JToken.FromObject(new { start = "some", end = "somedata" });
var newjson = jObj.ToString( Newtonsoft.Json.Formatting.Indented);