2013-07-25 34 views
0

我需要以下列格式來創建的JSON結構:如何將對象添加到c#中的字典?

{ 
    "test": [ 
     { 
      "mode": "2", 
      "test": "test3" 
     }, 
     { 
      "mode": "1", 
      "test": "test3" 
     } 
    ] 
} 

所以每當創建JSON結構,應當附加到測試元件。

所以最初我只值:

string [email protected]"{""testfun"": [ {""mode"": ""2"", ""test"": ""test3"" } ]}"; 

Dictionary<string, object> objtestnew2 = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json); 

所以,當我得到下一個JSON結構,以現有的字典元素我怎麼能追加?

回答

0

拆分你的字典創建,並將反序列化分成兩個不同的步驟。

第一次調用該方法時,應該查看字典是否存在,以及是否不創建字典。如果它確實存在,則可以將反序列化的數據追加到該字典中。

+0

你能提供一些樣品嗎? –

0

您可以反序列化第二個字典,然後將其合併到第一個字典中。最簡單的方法是一個簡單的循環:

string [email protected]"{""testfun"": [ {""mode"": ""2"", ""test"": ""test3"" } ]}"; 
Dictionary<string, object> dict = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(json); 

string [email protected]"{""testfun"": [ {""mode"": ""1"", ""test"": ""test3"" } ]}"; 
Dictionary<string, object> dict2 = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(json2); 

// loop through and update/add the items to the first dictionary 
foreach(var item in dict2) 
    dict1[item.Key] = item.Value;