We’re calling an API that returns JSON data structured as follows:
[
{
"firstName": "Bill",
"lastName": "Gates",
"email": "[email protected]"
},
{
"firstName": "Steve",
"lastName": "Balmer",
"email": "[email protected]"
}
]
After copying this data, and using the "Paste JSON as Classes" option in Visual Studio 2022, we have the following class:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string firstName { get; set; }
public string lastName { get; set; }
public string email { get; set; }
}
If we run the following test, our employees object contains 2 elements, but the value for each element is NULL.
string sJSON = @"[{""firstName"":""Bill"",""lastName"":""Gates"",""email"":""[email protected]""},{""firstName"":""Steve"",""lastName"":""Balmer"",""email"":""[email protected]""}]";
Rootobject[] employees = JsonSerializer.Deserialize<Rootobject[]>(sJSON);
Any idea what is wrong here?
2
Answers
First of all, your class should have different structure:
Then to deserialize use:
Also you can take a look here JsonPropertyAttribute
Based on your Json Rootobject should be an array.
You can use Convert Json to C# Classes Online to generate models for your Json.