Home > Net >  JSON value deserialize to C# Object in .NET Core
JSON value deserialize to C# Object in .NET Core

Time:10-18

I am trying to get the data from API (https://localhost:7270/api/GetEmployees). After getting all required data from the API I just want to deserialize into a C# Object and need to show in HTML page.

This is the JSON data

"{\"data\":[{\"id\":1,\"firstName\":\"Sandanuwan\",\"lastName\":\"Dharmarathna\",\"address\":\"Kurunegala\",\"dob\":\"2022-08-23T22:20:00\",\"age\":26,\"class\":\"10 B\",\"emailAddress\":\"[email protected]\",\"department\":{\"id\":2,\"departmentName\":\"HR\"}},{\"id\":2,\"firstName\":\"Anna\",\"lastName\":\"Merry\",\"address\":\"London\",\"dob\":\"2022-04-20T00:00:00\",\"age\":23,\"class\":\"7 A\",\"emailAddress\":\"[email protected]\",\"department\":{\"id\":1,\"departmentName\":\"Account\"}}],\"success\":true,\"message\":\"Successfully received all Employees Details\"}"

to deserialize above JSON data I have created C# classes like below.

Employee Class

public class Employee
    {
        public int Id { get; set; }        
        public string FirstName { get; set; } = string.Empty;       
        public string LastName { get; set; } = string.Empty;    
        public string Address { get; set; } = string.Empty;      
        public DateTime DOB { get; set; }    
        public int Age { get; set; }
        public string Class { get; set; } = string.Empty;    
        public string EmailAddress { get; set; } = string.Empty;     
        public Department Department { get; set; }
    }

Department Class

public class Department
    {
        public int Id { get; set; }       
        public string DepartmentName { get; set; } = string.Empty;
    }

Root Class

public class Root
{
    public List<Employee> Data { get; set; }
    public bool Success { get; set; }
    public string Message { get; set; }
}

Controller Index Method

 public async Task<IActionResult> Index()
        {
            List<Root> employeeList = new List<Root>();
            using (var httpClient = new HttpClient())
            {
                using (var response = await httpClient.GetAsync("https://localhost:7270/api/GetEmployees"))
                {
                    string apiResponse = await response.Content.ReadAsStringAsync();
                    employeeList = JsonConvert.DeserializeObject<List<Root>>(apiResponse);
                }
            }
            return View(employeeList);
        }

Index Html Page

<table >
    <thead>
        <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Date Of Birth</th>
            <th>Age</th>
            <th>Class</th>
            <th>Email Address</th>
            <th>Department</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var r in Model)
        {
            <tr>
                <td>@r.Data[0].Id</td>
                <td>@r.Data[1].FirstName</td>
            </tr>
        }
    </tbody>
</table>

But after run Web Application I am getting following error.

An unhandled exception occurred while processing the request.
JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[EmployeeWeb.Models.Root]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'data', line 1, position 8.

According to my understand error is coming from this line

employeeList = JsonConvert.DeserializeObject<List<Root>>(apiResponse);

So, Could someone can help me to resolve this issue. Thanks

CodePudding user response:

Deserialize apiResponse to Root, not List<Root>:

List<Employee> employeeList = new List<Employee>();
...
var root = JsonConvert.DeserializeObject<Root>(apiResponse);
employeeList = root.Data;
  • Related