1

Cordial saludo...

Estoy intentando realizar lo siguiente en .net:

Consumir un .json desde: https://recruiting-api.newshore.es/api/flights/0

Y eso me retorna una lista de atributos del siguiente tipo:

"departureStation":"XXX","arrivalStation":"XXX","flightCarrier":"XX","flightNumber":"XXXX","price":XXX

Tengo 2 clases:

1 -> Transport(FlightCarrier, FlightNumber) 2 -> Flight(Transport,Origin,Destination, Price)

  • Flight contiene a la clase transport

Lo que yo quiero es saber como hago para consumir el Json y que todos los objetos se queden en List<Flight>

La idea que yo tengo es recorrer el json con un for y crear los objetos manualmente... Pero no se sí es lo correcto y existe otra forma... Soy programador Python y apenas estoy aprendiendo .NET

Alguien puede ayudarme?

Este es el codigo que tengo hasta el momento:

using System.Net.Http.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;

string FlyURLsData = "https://recruiting-api.newshore.es/api/flights/0";
HttpClient client;
client = new HttpClient();
using var httpResponse = await client.GetAsync(FlyURLsData, HttpCompletionOption.ResponseHeadersRead);
string jsonStr = "";
jsonStr = await httpResponse.Content.ReadAsStringAsync();

var jsonObj = JsonNode.Parse(jsonStr);
JsonArray array = new JsonArray(jsonObj);

//Aqui hay que mapear


public class Flight
{
    public Transport Transport { get; set; }
    public string Origin { get; set; }
    public string Destination { get; set; }
    public double Price { get; set; }

    public Flight(Transport Transport, string Origin, string Destination, double Price)
    {
        this.Transport = Transport;
        this.Origin = Origin;
        this.Destination = Destination;
        this.Price = Price;
    }


}


public class Transport
{

    public string FlightCarrier { get; set; }
    public string FlightNumber { get; set; }

    public Transport()
    {
    }

}

1 respuesta 1

0

Una manera sería que crearas una clase que refleje fielmente el JSON, algo como esto:

public class FlightsDTO
{
    public string DepartureStation { get; set; }
    public string ArrivalStation { get; set; }
    public double Price { get; set; }
    public string FlightCarrier { get; set; }
    public string FlightNumber { get; set; }

    public Flight ToFlight()
    {
        return new Flight(new Transport()
        {
            FlightCarrier = FlightCarrier,
            FlightNumber = FlightNumber,
        }, DepartureStation, ArrivalStation, Price);
    }
        
}

En esta clase además incluimos una función que nos retorne Flight que sería el tipo de objeto que estas buscando.

Opcionalmente podrías crear una extensión para convertir una lista del tipo List<FlightsDTO> a List<Flight>

Algo así:

public static class ExtencionesList
{
    public static IEnumerable<Flight> TotFlights(this List<FlightsDTO> vuelos)
    {
        foreach (var v in vuelos)
            yield return v.ToFlight();
    }
}

Entonces tu código completo quedaría de esta manera:

internal class Program
{
    static async Task Main(string[] args)
    {
        string FlyURLsData = "https://recruiting-api.newshore.es/api/flights/0";
        HttpClient client = new HttpClient();
        var Flights = (await client.GetFromJsonAsync<List<FlightsDTO>>(FlyURLsData))?.TotFlights();
    }
}
public static class ExtencionesList
{
    public static IEnumerable<Flight> TotFlights(this List<FlightsDTO> vuelos)
    {
        foreach (var v in vuelos)
            yield return v.ToFlight();
    }
}
public class FlightsDTO
{
    public string DepartureStation { get; set; }
    public string ArrivalStation { get; set; }
    public double Price { get; set; }
    public string FlightCarrier { get; set; }
    public string FlightNumber { get; set; }

    public Flight ToFlight()
    {
        return new Flight(new Transport()
        {
            FlightCarrier = FlightCarrier,
            FlightNumber = FlightNumber,
        }, DepartureStation, ArrivalStation, Price);
    }
        
}
public class Flight
{
    public Transport Transport { get; set; }
    public string Origin { get; set; }
    public string Destination { get; set; }
    public double Price { get; set; }

    public Flight(Transport Transport, string Origin, string Destination, double Price)
    {
        this.Transport = Transport;
        this.Origin = Origin;
        this.Destination = Destination;
        this.Price = Price;
    }
}

public class Transport
{
    public string FlightCarrier { get; set; }
    public string FlightNumber { get; set; }
}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.