Reputation: 173
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 being 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 which 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.
Upvotes: 1
Views: 599
Reputation: 1055
I was dealing with a similar issue and my solution was to add the JsonProperty attribute as well. My JSON field name was thumbnail-url-base
.
I used Edit > Paste Special > Paste JSON as classes in Visual Studio to create my class.
[JsonProperty("thumbnail-url-base")]
public string thumbnailurlbase { get; set; }
If anyone is dealing with a similar issue where your field name contains a hyphen, you can also check out this stackoverflow question -> Can you have a property name containing a dash
Upvotes: 0
Reputation: 14880
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; }
}
Upvotes: 3