使用C#从随机用户API检索数据

时间:2019-09-17 10:43:15

标签: c# json api

我正在尝试使用C#(我是新来的)从随机用户API(https://api.randomuser.me/)接收数据。我有一个React前端,并且能够成功检索并渲染一个人的性别,一个人的位置。但是,在进一步嵌套的细节(例如某个人的名字)方面,我感到很挣扎。目前,我的后端代码是:

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

我试图通过添加以下内容来检索某人的名字:

Name = rawData.Results.Select(x => x.Name)Name = rawData.Results.Select(x => x.Name.First),但这不是在检索数据。有谁能帮我从随机用户API JSON中选择名字?

谢谢!

1 个答案:

答案 0 :(得分:3)

您的问题是您需要更改此行:

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

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

您应该创建一个新的返回类型类,并将其映射到您要返回的类中。.从人员分配:

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

返回

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

您还需要包括以下用于反序列化字符串的类:

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