0

I am trying to receive data from the Random User API (https://api.randomuser.me/) with C# (which I am new to). I have a React front end and am able to successfully retrieve and render gender of a person, location of a person. However, I am struggling when it comes to the details that are further nested, such as the first name of a person. My backend code at the moment is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace RandomPersonGenerator.Controllers
{
    [Route("api/[controller]")]
    public class GeneratorController : Controller
    {
        [HttpGet("[action]")]
        public async Task<IActionResult> Generate()
        {
            using (var client = new HttpClient())
            {
                try
                {
                    client.BaseAddress = new Uri("https://api.randomuser.me");
                    var response = await client.GetAsync("https://api.randomuser.me");
                    response.EnsureSuccessStatusCode();

                    var stringResult = await response.Content.ReadAsStringAsync();
                    var rawData = JsonConvert.DeserializeObject<PersonAPIResponse>(stringResult);
                    return Ok(new
                    {
                        Gender = rawData.Results.Select(x => x.Gender)
                    });
                }

                catch (HttpRequestException httpRequestException)
                {
                    return BadRequest($"Error generating person: {httpRequestException.Message}");
                }
            }
        }
    }

    public class PersonAPIResponse
    {
        public IEnumerable<PersonDescription> Results { get; set; }
    }

    public class PersonDescription
    {
        public string Gender { get; set; }
    }
}

I have tried to retrieve the first name of a person by adding:

Name = rawData.Results.Select(x => x.Name) and Name = rawData.Results.Select(x => x.Name.First) but this is not retrieving the data. Is anyone able to help me select the first name from the Random User API JSON?

Thank you!

0

2 Answers 2

3

Your problem is that you need to change this line:

var rawData = JsonConvert.DeserializeObject<PersonAPIResponse>(stringResult);

to

RootObject person = JsonConvert.DeserializeObject<RootObject>(stringResult);

You should create a new return type class and map into that, what you want to return.. assigning from person:

public class PersonAPIResponse
{
    //.... your own properties 
}

Return

return Ok(new PersonAPIResponse
              {
                 Gender = person.results[0].gender, //first result
              });

You also need to include the following classes for deserializing the string:

public class Name
{
    public string title { get; set; }
    public string first { get; set; }
    public string last { get; set; }
}

public class Coordinates
{
    public string latitude { get; set; }
    public string longitude { get; set; }
}

public class Timezone
{
    public string offset { get; set; }
    public string description { get; set; }
}

public class Location
{
    public string street { get; set; }
    public string city { get; set; }
    public string state { get; set; }
    public int postcode { get; set; }
    public Coordinates coordinates { get; set; }
    public Timezone timezone { get; set; }
}

public class Login
{
    public string uuid { get; set; }
    public string username { get; set; }
    public string password { get; set; }
    public string salt { get; set; }
    public string md5 { get; set; }
    public string sha1 { get; set; }
    public string sha256 { get; set; }
}

public class Dob
{
    public DateTime date { get; set; }
    public int age { get; set; }
}

public class Registered
{
    public DateTime date { get; set; }
    public int age { get; set; }
}

public class Id
{
    public string name { get; set; }
    public object value { get; set; }
}

public class Picture
{
    public string large { get; set; }
    public string medium { get; set; }
    public string thumbnail { get; set; }
}

public class Result
{
    public string gender { get; set; }
    public Name name { get; set; }
    public Location location { get; set; }
    public string email { get; set; }
    public Login login { get; set; }
    public Dob dob { get; set; }
    public Registered registered { get; set; }
    public string phone { get; set; }
    public string cell { get; set; }
    public Id id { get; set; }
    public Picture picture { get; set; }
    public string nat { get; set; }
}

public class Info
{
    public string seed { get; set; }
    public int results { get; set; }
    public int page { get; set; }
    public string version { get; set; }
}

public class RootObject
{
    public List<Result> results { get; set; }
    public Info info { get; set; }
}
8
  • Thank you so much for explaining that. I have implemented in my code, however I have the following error "RootObject does not contain a definition for Result' in the line: Gender = person.Result.Gender Please could you also explain what is supposed to now be in public class PersonAPIResponse? I am a bit confused by this bit :( Sorry
    – juemura7
    Sep 17, 2019 at 12:17
  • 1
    PersonAPIResponse is what you want to return... its up to you, aka Gender string could be added or anything which you want to map from person. if you have the debugger attached it will tell you the names...when i used an online tool to create the classes from you json it lower basically all the property names, normally this would be CamelCase, anyway the prop off person is 'results' you can see this if you look at the RootObject, PS you can rename RootObject to what ever you like. aka person.Result.Gender would be person.results[0].gender remember results is a collection.
    – Seabizkit
    Sep 17, 2019 at 12:38
  • I updated the line in question for more clarity and correctness it was just sudo code
    – Seabizkit
    Sep 17, 2019 at 12:44
  • Thanks @Seabizkit - again very helpful. I am still however getting an error: List<Result> does not contain a definition of gender on the same line
    – juemura7
    Sep 17, 2019 at 17:28
  • 1
    its because results is a collection and [index] is how you access an entry in an array, you need to look into array's...., as its a List you could of done results.First().Gender it would be the same ish thing... but again you need to research and look in this stuff
    – Seabizkit
    Sep 18, 2019 at 9:06
0
{
    public class Name
    {
        public string Title { get; set; }
        public string First { get; set; }
        public string Last { get; set; }
    }

    public class Result
    {
        public Name Name { get; set; }
    }

    public class Person
    {
        public List<Result> Results { get; set; }
    }

    public async Task<Name> GetPersonAsync()
    {
        HttpClient client = new HttpClient
        {
            BaseAddress = new Uri("https://api.randomuser.me")
        };
        HttpResponseMessage response = await client.GetAsync("https://randomuser.me/api/");
        response.EnsureSuccessStatusCode();
 
        var stringResult = await response.Content.ReadAsStringAsync();
        Person root = JsonConvert.DeserializeObject<Person>(stringResult);
        Console.WriteLine(root.Results[0].Name.Last);
        return root.Results[0].Name;
    }

}
1
  • 1
    Please don’t just dump code here. Can you edit to include an explanation of what you’re doing and how this contributes to this thread? Dec 15, 2021 at 18:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.