如何在c#中向字典添加对象?
我需要创建以下格式的JSON结构:如何在c#中向字典添加对象?,c#,json,C#,Json,我需要创建以下格式的JSON结构: { "test": [ { "mode": "2", "test": "test3" }, { "mode": "1", "test": "test3" } ] } 因此,无论何时创建JSON结构,都应该将其附加到测试元素 因此,最初我将只具有以下值: string json=@"{"
{
"test": [
{
"mode": "2",
"test": "test3"
},
{
"mode": "1",
"test": "test3"
}
]
}
因此,无论何时创建JSON结构,都应该将其附加到测试元素
因此,最初我将只具有以下值:
string json=@"{""testfun"": [ {""mode"": ""2"", ""test"": ""test3"" } ]}";
Dictionary<string, object> objtestnew2 = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
string json=@“{”“testfun”“:[{”“mode”“:”“2”“test”“:”“test3”“}];
Dictionary objtestnew2=新的JavaScriptSerializer()。反序列化(json);
那么,当我将下一个JSON结构添加到现有的dictionary元素时,我该如何添加呢?将字典的创建和反序列化分为两个不同的步骤
第一次调用该方法时,应该查看字典是否存在,以及字典是否没有创建。如果确实存在,则可以将反序列化数据附加到该字典。可以反序列化第二个字典,然后将其合并到第一个字典中。最简单的方法是一个简单的循环:
string json=@"{""testfun"": [ {""mode"": ""2"", ""test"": ""test3"" } ]}";
Dictionary<string, object> dict = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(json);
string json2=@"{""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;
string json=@“{”“testfun”“:[{”“mode”“:”“2”“test”“:”“test3”“}];
Dictionary dict=(新的JavaScriptSerializer());
字符串json2=@“{”“testfun”“:[{”“mode”“:”“1”“test”“:”“test3”“}];
Dictionary dict2=(新的JavaScriptSerializer());
//循环浏览并更新/添加项目到第一个字典
foreach(dict2中的var项目)
dict1[item.Key]=item.Value;
您能提供一些样品吗?