user11196706
user11196706

Reputation:

Retrieving data from Random User API with C#

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!

Upvotes: 0

Views: 1609

Answers (2)

Desi Dev
Desi Dev

Reputation: 1

{
    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;
    }

}

Upvotes: 0

Seabizkit
Seabizkit

Reputation: 2415

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; }
}

Upvotes: 2

Related Questions