JSON映射到C#类

时间:2015-08-12 07:12:16

标签: c# json

我有一个像这样的JSON:

{
"Site 1": [
    {
        "Stuff": [
            "detergent",
            "det1"
        ],
        "productLine": "Hay",
        "revenue": {
            "1": 3123,
            "2": 123123,
            "3": 123123
        }
    },
    {
        "Stuff": [
            "detergent",
            "det2"
        ],
        "productLine": "Machine",
        "revenue": {
            "1": 343123,
            "2": 1231321323,
            "3": 321
        }
    }
],
"Site 2": [
    {
        "Stuff": [
            "detergent",
            "det1"
        ],
        "productLine": "Hay",
        "revenue": {
            "1": 111,
            "2": 123123,
            "3": 3213
        }
    },
    {
        "Stuff": [
            "detergent",
            "det2"
        ],
        "productLine": "Machine",
        "revenue": {
            "1": 11123,
            "2": 3255,
            "3": 6575
        }
    }
]
}

我想将此映射到C#类但我的问题是名称Site1site2我认为应该是类名吗?有没有办法将其表示为C#对象?

2 个答案:

答案 0 :(得分:4)

您的根对象实际上是Dictionary<string, List<YourClass>>YourClass将如下所示:

public class YourClass
{
    public string[] Stuff { get; set; }
    public string productLine { get; set; }
    public Dictionary<string, int> revenue { get; set; }
}

现在你可以像这样反序列化你的json:

var dic = JsonConvert.DeserializeObject<Dictionary<string, List<YourClass>>>("Your json string goes here...");

答案 1 :(得分:0)

在映射与json相同的对象图的c#类中,您可以向Class和属性添加属性以准确映射json,例如小写json属性等。

请参阅:http://www.newtonsoft.com/json/help/html/SerializationAttributes.htm