2016-12-01 61 views
-2

我有一些JSON,看起來像這樣JSON屬性:添加使用Newtonsoft.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" 
    } 
} 

我想增加一個第四步因此最終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); 

OR 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); 
+0

不錯的觀察,坦率地說,我不知道'IDictionary'的實現 – Sid

+0

謝謝你做的伎倆 – user299967