I am new to .NET Core and trying to figure things out; practising how to consume APIs with Flurl. With this endpoint https://jsonplaceholder.typicode.com/posts which returns JSON array, I tried the following code, but the list consisted of dynamics which I was unable to convert. Can anyone advise how to cast the dynamic into a proper post object?
public class PostsApiClient
{
public async Task<IEnumerable<PostInput>> GetPosts()
{
var response = await "https://jsonplaceholder.typicode.com/posts".GetJsonListAsync();
IEnumerable<Post> listOfPosts = response.Select(post => new Post
{
Title = post.Title,
Body = post.Body
});
return listOfPosts;
}
public class Post
{
public int UserId { get; set; }
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
}
GetJsonListAsync
was specifically designed to return a list of dynamics. There isn't a typed (generic) equivalent specifically for lists, but all you need to do is provide a collection type to GetJsonAsync
. In your case, this should work:
public async Task<IEnumerable<Post>> GetPosts()
{
return await url.GetJsonAsync<Post[]>();
}