Reputation: 13
This is my first jump into C#, Blazor, and razor pages and I am trying to make a simple page that will show the requested JSON information in a readable form for the user. However, I am getting an error when I run this code that says it cannot be converted?
public interface IJokeService
{
Task<IEnumerable<Joke>> GetJokes();
}
public class JokeService : IJokeService
{
private readonly HttpClient httpClient;
public JokeService (HttpClient httpClient)
{
this.httpClient = httpClient;
}
public async Task<IEnumerable<Joke>> GetJokes()
{
return await httpClient.GetFromJsonAsync<Joke[]>("/random_joke");
}
}
@page "/fetchjokes"
@using GettingStarted.Shared
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using GettingStarted.Client.Services
@attribute [Authorize]
<h3>FetchJokes</h3>
@if (Jokec == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>General</th>
<th>Setup</th>
<th>punchline</th>
</tr>
</thead>
<tbody>
@foreach (var Jokes in Jokec)
{
<tr>
<td>@Jokes.id</td>
<td>@Jokes.type</td>
<td>@Jokes.setup</td>
<td>@Jokes.punchline</td>
</tr>
}
</tbody>
</table>
}
@inject IJokeService jokeService
@code
{
public IEnumerable<Joke> Jokec;
protected override async Task OnInitializedAsync()
{
Jokec = (await jokeService.GetJokes()).ToList();
}
}
If anyone could help shine some light on what I am doing wrong or enlighten me with a better way of doing this, I would greatly appreciate it.
the JSON I'm attempting to receive https://official-joke-api.appspot.com/random_joke
Upvotes: 1
Views: 1802
Reputation: 273464
The link yields a single joke.
You tell the deserialzier to expect an array of jokes.
public async Task<Joke> GetJokes()
{
return await httpClient.GetFromJsonAsync<Joke>("/random_joke");
}
Upvotes: 4