简体   繁体   English

C#,反序列化json

[英]C#, Deserialize json

I have a json like the example bellow and I'm using C# with json.net. 我有一个像示例波纹管这样的json,并且我在json.net中使用C#。 I'm trying to deserialize this json into a object, but it's not working. 我正在尝试将此json反序列化为对象,但无法正常工作。

{
    "classes": [{
        "id": 1,
        "mask": 1,
        "powerType": "rage",
        "name": "Warrior"
    }, {
        "id": 2,
        "mask": 2,
        "powerType": "mana",
        "name": "Paladin"
    }, {
        "id": 3,
        "mask": 4,
        "powerType": "focus",
        "name": "Hunter"
    }, {
        "id": 4,
        "mask": 8,
        "powerType": "energy",
        "name": "Rogue"
    }, {
        "id": 6,
        "mask": 32,
        "powerType": "runic-power",
        "name": "Death Knight"
    }, {
        "id": 12,
        "mask": 2048,
        "powerType": "fury",
        "name": "Demon Hunter"
    }]
}

1) I created a class: 1)我创建了一个类:

public class ClassJson
{
    [JsonProperty(PropertyName = "classes")]
    public Class Class { get; set; }
}

2) The second class: 2)第二类:

public class Class
{
    [JsonProperty(PropertyName = "id", NullValueHandling = NullValueHandling.Ignore)]
    public int Id { get; set; }

    [JsonProperty(PropertyName = "powerType", NullValueHandling = NullValueHandling.Ignore)]
    public string PowerType { get; set; }

    [JsonProperty(PropertyName = "name", NullValueHandling = NullValueHandling.Ignore)]
    public string Name { get; set; }
}

I call the Api, get the json and I simply call JsonConvert.DeserializeObject<List<ClassJson>>(json) . 我调用Api,获取json,然后简单地调用JsonConvert.DeserializeObject<List<ClassJson>>(json) Nothing happens, no errors. 什么都没有发生,没有错误。

Can someone give me a tip in order to structure better the classes? 有人可以给我小费以更好地组织课堂吗?

Try this instead because classes is supposed to be an array: 请改用此方法,因为classes应该是数组:

public class ClassJson
{
    [JsonProperty(PropertyName = "classes")]
    public Class[] classes { get; set; }
}

You do not need to write the classes to represent JSON manually. 您无需编写用于手动表示JSON的类。 Refer my answer here on how to create a class representation of your JSON. 在这里参考我的答案以了解如何创建JSON的类表示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM