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!