Search code examples
jsonflurl

Web api call returns json data with empty fields


I'm getting some json data using Flurl (function below). My problem is that this returns the expected fields but not the actual data:

screenshot

The json is at: https://jsonplaceholder.typicode.com/users

The exact same function worked fine in a separate standalone test app that did not use Microsoft.AspNetCore.Mvc.

Any ideas why it would return the fields but not the data? Thanks.

using System;
using Test.API.Constants;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Flurl.Http;

namespace Test.API.Controllers
{
    public class TestController
    {
        [Route(ApiControllerRoutes.Test.test)]
        [HttpGet]
        public async Task<dynamic> GetAsync()
        {
            try
            {
                string url = "https://jsonplaceholder.typicode.com/users";
                return await url.GetJsonListAsync();
            }
            catch (Exception e)
            {
            }
        }
    }
}

Solution

  • GetJsonListAsync (without a generic argument) returns Task<IList<dynamic>>, so the easiest fix is to use the same return type from your controller, instead of Task<dynamic>.

    If you want this to be a bit more robust and type-safe, I would skip dynamics altogether and create a User class, then use GetJsonListAsync<User>() and return Task<IList<User>> in your controller. I see there's nested objects involved so you'd actually need several classes to represent the whole structure. json2csharp is a great tool to assist with this. Just paste in JSON represention of a single user (not the whole list) and it'll generate everything for you.