[英]Deserializing JSON array into C# object (TFL api)
I am trying to deserialize the London Underground API into C#.我正在尝试将伦敦地铁 API 反序列化为 C#。 The API endpoint looks like this https://api.tfl.gov.uk/Line/Mode/tube/Status and it is an array of JSON objects.
API 端点类似于https://api.tfl.gov.uk/Line/Mode/tube/Status ,它是一个 JSON 对象数组。 I want to deserialize into a C# object but can't work out how to do this.
我想反序列化为 C# 对象,但不知道如何执行此操作。 This is what I have so far:
这是我到目前为止:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace TFL.Controllers
{
[Route("api/[controller]")]
public class TubeApi : Controller
{
[HttpGet("[action]")]
public async Task<IActionResult> GetTubeStatus()
{
using (var client = new HttpClient())
{
try
{
client.BaseAddress = new Uri("https://api.tfl.gov.uk");
var response = await client.GetAsync("/Line/Mode/tube/Status");
response.EnsureSuccessStatusCode();
var stringResult = await response.Content.ReadAsStringAsync();
var rawData = JsonConvert.DeserializeObject<List<RootObject>>(stringResult);
return Ok(new
{
LineId = rawData.name
});
}
catch (HttpRequestException httpRequestException)
{
return BadRequest("Error getting data");
}
}
}
}
public class RootObject
{
public string name { get; set; }
public List<LineStatus> lineStatuses { get; set; }
}
public class LineStatus
{
public string statusSeverityDescription { get; set; }
}
}
However I get the following build error:但是我收到以下构建错误:
List does not contain a definition for name.
列表不包含名称的定义。
I am new to JSON and have never had to deserialize from an array, usually from JSON {"name":"value"}
.我是 JSON 的新手,从来没有从数组中反序列化,通常是从 JSON
{"name":"value"}
。
Can anyone please help me to see where I have gone wrong here?谁能帮我看看我哪里出错了?
Thanks.谢谢。
Your rawData
is a List<RootObject>
.您的
rawData
是一个List<RootObject>
。 A List<T>
doesn't have any properties named name
. List<T>
没有任何名为name
属性。
Using var
has his advantages and disadvantages, if you had used the right type I think you would have seen your mistake.使用
var
有他的优点和缺点,如果你使用了正确的类型,我想你会看到你的错误。
If you want to get the name of a line in your List<RootObject>
you have to access one of its element.如果您想获取
List<RootObject>
中某行的名称,则必须访问其元素之一。 You can do it through multiple ways like :您可以通过多种方式做到这一点,例如:
rawData[0].name;
or或者
rawData.Find(x => x.name.Equals("MyLine"));
or或者
rawData.IndexOf("MyLine");
You can look at List in C# .您可以查看C#中的List 。
Hope this will help you.希望这会帮助你。
Try the below code to get all names尝试以下代码以获取所有名称
var result = (from c in rawData select (new
{
LineId = c.name
})).ToList();
return Ok(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.