如何使用动态属性名称反序列化JSON对象?

时间:2014-07-05 16:22:59

标签: c# json

这是我从远程服务器获取的JSON ......如何为此创建一个C#对象?

{
    "payload":
    {
        "one":
        {
            "x": 1
        },
        "two":
        {
            "x": 2
        },
        "three":
        {
            "x": 3
        }
    }
}

http://json2csharp.com/创建了三个类型“one”,“two”和“three”......但这些是动态值。我可能会在下一个请求中得到“四个”,“五个”,“六个”

1 个答案:

答案 0 :(得分:5)

您可以使用Dictionary<string,YourClass>

string json = @"{ ""payload"": { ""one"": { ""x"":1 }, ""two"": { ""x"":2 }, ""three"": { ""x"":3 } } }";
var  root = JsonConvert.DeserializeObject<RootObject>(json);

public class Item
{
    public int x { get; set; }
}

public class RootObject
{
    public Dictionary<string,Item> payload { get; set; }
}