更新
鑑於你的更新類和更新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