更新
鉴于你的更新类和更新JSON,你会怎么做:
public class RootObject
{
public Root root { get; set; }
}
public class Root
{
public int id {set;get;}
public string name {set;get;}
public Dictionary<string, Container> containers { get; set; }
}
public class Container
{
public int id {set; get;}
public string name {set;get;}
public int value {set;get;}
}
而且使用它像:
var root = JsonConvert.DeserializeObject<RootObject>(json);
注意,"root"
财产的JSON需要额外的间接级别,这是我们通过RootObject
类提供的。你可能会想你的Root
重命名为更具描述性的像RootContainer
。
更新2
的JSON在这个问题再次被修改,以消除"root"
属性,因此RootObject
是不必要的,你只需要做:
var root = JsonConvert.DeserializeObject<Root>(json);
原来的答案
假设你的嵌套containers
也是Container
类型,你可以直接de它们序列作为Dictionary<string, Container>
属性:
public class Container
{
public int id { set; get; }
public string name { set; get; }
public int? value { set; get; } // Null when the property was not present in the JSON.
public Dictionary<string, Container> containers { get; set; }
}
你会用它喜欢:
public static void Test()
{
string json = @"
{
""id"" : 3223,
""name"" : ""position 3223"",
""containers"" : {
""container_demo"" : {
""id"" : 12,
""name"" : ""demo"",
""value"" : 34
},
""different_name_1"" : {
""id"" : 33,
""name"" : ""demo 3"",
""value"" : 1
},
""another_contaier"" : {
""id"" : 1,
""name"" : ""another demo"",
""value"" : 34
}
}
}";
var container = JsonConvert.DeserializeObject<Container>(json);
JsonSerializerSettings settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
Debug.WriteLine(JsonConvert.SerializeObject(container, Formatting.Indented, settings));
}
这将产生输出:
{
"id": 3223,
"name": "position 3223",
"containers": {
"container_demo": {
"id": 12,
"name": "demo",
"value": 34
},
"different_name_1": {
"id": 33,
"name": "demo 3",
"value": 1
},
"another_contaier": {
"id": 1,
"name": "another demo",
"value": 34
}
}
正如你所看到的,所有的数据被反序列化和序列化成功。
'containers'属性是泛型类型吗?请详细说明你的课程。 – 2015-03-03 00:24:21
我不知道它是通用的服务器上,但在我的C#实现它不是通用的。 – user2598575 2015-03-03 00:27:08
这是错别字对不起。我已修复 – user2598575 2015-03-03 00:40:45