I have this simple JSON
{
"persons": [{
"firstname": "Brad",
"lastname": "Pitt"
}, {
"firstname": "George",
"lastname": "Clooney"
}, {
"firstname": "Matt",
"lastname": "Damon"
}]
}
And this are my classes in C#:
public class PersonObject
{
[JsonProperty(PropertyName = "persons")]
public List<Person> Persons { get; set; }
}
public class Person
{
[JsonProperty(PropertyName = "firstname")]
public string Firstname { get; set; }
[JsonProperty(PropertyName = "lastname")]
public string Lastname { get; set; }
}
For some reason it always return null... I really can't see what is wrong with this... With the JsonConvert.DeserializeObject
is nothing wrong becouse it works for other JSON strings.
_PersonsList = JsonConvert.DeserializeObject<List<PersonObject>>(data);
Your data doesn't contain a List<PersonObject>
- it contains a single PersonObject
which in turn contains a List<Person>
. So this works fine:
var json = File.ReadAllText("test.json");
var obj = JsonConvert.DeserializeObject<PersonObject>(json);
Console.WriteLine(obj.Persons[0].Firstname); // Prints Brad
With your current code, you shouldn't be getting a null reference back - you should be getting an exception, like this:
Unhandled Exception: Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[PersonObject]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
If you are seeing a null reference, that suggests you're swallowing exceptions somewhere, which is worth fixing separately.
See more on this question at Stackoverflow