Я пытаюсь получить данные из API (https://localhost:7270/api/GetEmployees). После получения всех необходимых данных из API я просто хочу десериализовать объект С# и показать его на HTML-странице.
Это данные JSON
"{\"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\"}"
для десериализации вышеуказанных данных JSON я создал классы С#, как показано ниже.
Класс сотрудника
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; }
}
Класс отдела
public class Department
{
public int Id { get; set; }
public string DepartmentName { get; set; } = string.Empty;
}
Корневой класс
public class Root
{
public List<Employee> Data { get; set; }
public bool Success { get; set; }
public string Message { get; set; }
}
Метод индекса контроллера
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);
}
Индекс HTML-страницы
<table class = "table table-sm table-striped table-bordered m-2">
<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>
Но после запуска веб-приложения я получаю следующую ошибку.
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.
Насколько я понимаю, ошибка исходит из этой строки
employeeList = JsonConvert.DeserializeObject<List<Root>>(apiResponse);
Итак, может ли кто-нибудь помочь мне решить эту проблему. Спасибо
Десериализовать apiResponse для Root
, а не List<Root>
:
List<Employee> employeeList = new List<Employee>();
...
var root = JsonConvert.DeserializeObject<Root>(apiResponse);
employeeList = root.Data;
JSON экранирован. Вы уверены, что
GetEmployees
возвращает правильно закодированный объект json?