Maturano
Maturano

Reputation: 1023

C#, Deserialize json

I have a json like the example bellow and I'm using C# with json.net. I'm trying to deserialize this json into a object, but it's not working.

{
    "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:

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

2) The second class:

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). Nothing happens, no errors.

Can someone give me a tip in order to structure better the classes?

Upvotes: 0

Views: 72

Answers (1)

CodingYoshi
CodingYoshi

Reputation: 26989

Try this instead because classes is supposed to be an array:

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

You do not need to write the classes to represent JSON manually. Refer my answer here on how to create a class representation of your JSON.

Upvotes: 1

Related Questions