'The JSON value could not be converted to Model Blazor
First Blazor WASM app. I get an error while fetching data from Server:
System.Text.Json.JsonException: Deserialization failed for one of these reasons:
- Invalid property 'result' found within a JSON object that must only contain metadata >properties and the nested JSON array to be preserved.
- The JSON value could not be converted to WeatherBA.Shared.Dtos.ForecastReadDto[]. Path: >$.result | LineNumber: 0 | BytePositionInLine: 10.
FetchData.razor
@code {
private ForecastReadDto[]? forecasts;
protected override async Task OnInitializedAsync()
{
forecasts = await Http.GetFromJsonAsync<ForecastReadDto[]>("api/Forecast");
}
ForecastController.cs
public class ForecastController : ControllerBase
{
private readonly IMediator _mediator;
public ForecastController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet]
public ActionResult<IEnumerable<ForecastReadDto>> GetAllForecasts()
{
var request = new GetAllForecastsQuery();
var result = _mediator.Send(request);
return Ok(result);
}
}
GetAllForecastsQueryHandler.cs
...
public async Task<List<ForecastReadDto>> Handle(GetAllForecastsQuery request,
CancellationToken cancellationToken)
{
var forecasts = await _repo.GetAllAsync();
var forecastsOrdered = forecasts.OrderBy(x => x.Date);
return _mapper.Map<List<ForecastReadDto>>(forecasts);
}
SqlForecastRepo.cs
...
public Task<List<Forecast>> GetAllAsync()
{
return Task.FromResult(_context.Forecasts.ToList());
}
ForecastReadDto.cs
namespace WeatherBA.Shared.Dtos;
public class ForecastReadDto
{
public int Id { get; set; }
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string? Summary { get; set; }
}
An API Endpoint returns:
{
"result": [
{
"id": 3,
"date": "2022-01-01T00:00:00",
"temperatureC": 20,
"summary": "Sunny"
}
],
"id": 4639,
"exception": null,
"status": 5,
"isCanceled": false,
"isCompleted": true,
"isCompletedSuccessfully": true,
"creationOptions": 0,
"asyncState": null,
"isFaulted": false
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
