简体   繁体   中英

Deserializing JSON array into C# object (TFL api)

I am trying to deserialize the London Underground API into C#. The API endpoint looks like this https://api.tfl.gov.uk/Line/Mode/tube/Status and it is an array of JSON objects. I want to deserialize into a C# object but can't work out how to do this. 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"} .

Can anyone please help me to see where I have gone wrong here?

Thanks.

Your rawData is a List<RootObject> . A List<T> doesn't have any properties named name .

Using var has his advantages and disadvantages, if you had used the right type I think you would have seen your mistake.

If you want to get the name of a line in your List<RootObject> you have to access one of its element. 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# .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM