Ben Ben - 2 months ago 11
C# Question

json.net DeserializeObject not populating classes causing NullReferenceException

I'm get an answer from an API server in the format of JSON. I then try to deserialize it with json.net and call a few objects. This however is causing a NullReferenceException. During Debugging I indeed see that the classes starting from _507888780 are not beeing populated when deserializing the json string.
I hope someone of you can help me out with that.

The code I'm using to deserialize and call the objects:

string file = "{\"status\":\"ok\",\"meta\":{\"count\":1},\"data\":{\"507888780\":[{\"all\":{\"spotted\":467,\"hits_percents\":83,\"wins\":281,},\"tank_id\":2849},{\"all\":{\"spotted\":224,\"hits_percents\":63,\"wins\":32,},\"tank_id\":9473}]}}";
Rootobject rootobject = JsonConvert.DeserializeObject<Rootobject>(file);
Console.WriteLine(rootobject.data._507888780[1].tank_id);
Console.WriteLine(rootobject.data._507888780[1].all.hits_percents);


And the classes wich were automatically created by VS:

public class Rootobject
{
public string status { get; set; }
public Meta meta { get; set; }
public Data data { get; set; }
}
public class Meta
{
public int count { get; set; }
}
public class Data
{
public _507888780[] _507888780 { get; set; }
}
public class _507888780
{
public All all { get; set; }
public long tank_id { get; set; }
}
public class All
{
public long spotted { get; set; }
public long hits_percents { get; set; }
public long wins { get; set; }
}


I also put the testing project to .NET Fiddle so you can reproduce it more easy:
https://dotnetfiddle.net/gwSA1C
You'll also see the Json string in a more readable way in there.

Answer

JSON.Net isn't able to map the 507888780 property name in JSON to the _507888780 class property name. In these cases, you need to point the library in the good direction by adding a JsonProperty attribute:

public class Data
{
    [JsonProperty("507888780")]
    public _507888780[] _507888780 { get; set; }
}

.NET Fiddle