skip to Main Content

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


  1. First of all, your class should have different structure:

    public class Employee
    {
        public string FirstName { get; set; }
    
        public string LastName { get; set; }
    
        public string Email { get; set; }
    }
    

    Then to deserialize use:

    var options = new JsonSerializerOptions
    {
        PropertyNameCaseInsensitive = true
    };
    
    var employees = System.Text.Json.JsonSerializer.Deserialize<Employee[]>(json, options);
    

    Also you can take a look here JsonPropertyAttribute

    Login or Signup to reply.
  2. Based on your Json Rootobject should be an array.
    You can use Convert Json to C# Classes Online to generate models for your Json.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search