该问题出现在使用 Blazor WebAssembly 调用外部 API 中,当返回的 JSON 不在数组中时,Blazor 无法正确解析它,因此出现了无法工作的情况。
通过将返回的 JSON 嵌套在数组中,可以解决这个问题。下面是一个示例代码:
// 未嵌套在数组中的 JSON
{
"name": "John",
"age": 35
}
// 嵌套在数组中的 JSON
[
{
"name": "John",
"age": 35
}
]
下面是一个使用 Blazor WebAssembly 调用外部 API 并解析嵌套在数组中的 JSON 的示例:
@inject HttpClient httpClient
@code {
private WeatherForecast[] forecasts;
protected override async Task OnInitializedAsync()
{
var response = await httpClient.GetAsync("api/weatherforecast");
response.EnsureSuccessStatusCode();
var jsonString = await response.Content.ReadAsStringAsync();
forecasts = JsonSerializer.Deserialize(jsonString);
}
}
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
}