Получить значение из вложенного Json - PullRequest
0 голосов
/ 02 июня 2018

У меня есть Json, как показано ниже.

{
  "currency": "MYR",
  "results": [
    {
      "itineraries": [
        {
          "outbound": {
            "flights": [
              {
                "departs_at": "2018-06-03T06:25",
                "arrives_at": "2018-06-03T07:25",
                "origin": {
                  "airport": "PEN"
                },
                "destination": {
                  "airport": "KUL",
                  "terminal": "M"
                },
                "marketing_airline": "OD",
                "operating_airline": "OD",
                "flight_number": "2105",
                "aircraft": "738",
                "booking_info": {
                  "travel_class": "ECONOMY",
                  "booking_code": "Q",
                  "seats_remaining": 9
                }
              }
            ]
          },
          "inbound": {
            "flights": [
              {
                "departs_at": "2018-06-04T14:10",
                "arrives_at": "2018-06-04T15:10",
                "origin": {
                  "airport": "KUL",
                  "terminal": "M"
                },
                "destination": {
                  "airport": "PEN"
                },
                "marketing_airline": "OD",
                "operating_airline": "OD",
                "flight_number": "2108",
                "aircraft": "739",
                "booking_info": {
                  "travel_class": "ECONOMY",
                  "booking_code": "O",
                  "seats_remaining": 5
                }
              }
            ]
          }
        }
      ],
      "fare": {
        "total_price": "360.00",
        "price_per_adult": {
          "total_fare": "360.00",
          "tax": "104.00"
        },
        "restrictions": {
          "refundable": false,
          "change_penalties": true
        }
      }
    }
  ]
}

И я использую приведенный ниже код для получения значения из Json.Мне удалось получить "departs_at", "Arrives_at", "marketing_airline", но я не смог получить значение в "booking_info".

IOperations _obj = ClsOperations.GetOperations();
string url = "https://api.sandbox.amadeus.com/v1.2/flights/low-fare-search?apikey=" + APIKEY
    + "&origin=" + origin + "&destination=" + destination
    + "&departure_date=" + departureDate + "&return_date=" + returnDate
    + "&currency=" + currency + "&number_of_results=1";
string json = _obj.GetJsonResult(url);
JToken jToken = JToken.Parse(json);
JArray outBoundFlights = (JArray)jToken.SelectToken("results[0].itineraries[0].outbound.flights");
foreach (JToken obf in outBoundFlights)
{
    TravelPlan.Text += "Departs At: " + obf["departs_at"] + "<br/>";
    TravelPlan.Text += "Arrives At: " + obf["arrives_at"] + "<br/>";
    TravelPlan.Text += "Airline: " + obf["marketing_airline"] + "<br/>";
}
JArray outBoundFlightsBooking = (JArray)jToken.SelectToken("results[0].itineraries[0].outbound.flights.booking_info");
foreach (JToken obfb in outBoundFlightsBooking)
{
    TravelPlan.Text += "<br/>";
    TravelPlan.Text += "Travel Class: " + obfb["travel_class"] + "<br/>";
    TravelPlan.Text += "Seats Remaining: " + obfb["seats_remaining"] + "<br/>";
}

Я хотел бы спросить, насколько возможно я могу получить значение внутриbooking_info?Спасибо всем участникам, которые помогают.

Ответы [ 2 ]

0 голосов
/ 02 июня 2018
public class Origin
{
    public string airport { get; set; }
}

public class Destination
{
    public string airport { get; set; }
    public string terminal { get; set; }
}

public class BookingInfo
{
    public string travel_class { get; set; }
    public string booking_code { get; set; }
    public int seats_remaining { get; set; }
}

public class Flight
{
    public string departs_at { get; set; }
    public string arrives_at { get; set; }
    public Origin origin { get; set; }
    public Destination destination { get; set; }
    public string marketing_airline { get; set; }
    public string operating_airline { get; set; }
    public string flight_number { get; set; }
    public string aircraft { get; set; }
    public BookingInfo booking_info { get; set; }
}

public class Outbound
{
    public List<Flight> flights { get; set; }
}

public class Origin2
{
    public string airport { get; set; }
    public string terminal { get; set; }
}

public class Destination2
{
    public string airport { get; set; }
}

public class BookingInfo2
{
    public string travel_class { get; set; }
    public string booking_code { get; set; }
    public int seats_remaining { get; set; }
}

public class Flight2
{
    public string departs_at { get; set; }
    public string arrives_at { get; set; }
    public Origin2 origin { get; set; }
    public Destination2 destination { get; set; }
    public string marketing_airline { get; set; }
    public string operating_airline { get; set; }
    public string flight_number { get; set; }
    public string aircraft { get; set; }
    public BookingInfo2 booking_info { get; set; }
}

public class Inbound
{
    public List<Flight2> flights { get; set; }
}

public class Itinerary
{
    public Outbound outbound { get; set; }
    public Inbound inbound { get; set; }
}

public class PricePerAdult
{
    public string total_fare { get; set; }
    public string tax { get; set; }
}

public class Restrictions
{
    public bool refundable { get; set; }
    public bool change_penalties { get; set; }
}

public class Fare
{
    public string total_price { get; set; }
    public PricePerAdult price_per_adult { get; set; }
    public Restrictions restrictions { get; set; }
}

public class Result
{
    public List<Itinerary> itineraries { get; set; }
    public Fare fare { get; set; }
}

public class RootObject
{
    public string currency { get; set; }
    public List<Result> results { get; set; }
}

Это будет работать как шарм.

 string json = "{\"currency\": \"MYR\",  \"results\": [    {      \"itineraries\": [        {          \"outbound\": {            \"flights\": [              {                \"departs_at\": \"2018-06-03T06:25\",                \"arrives_at\": \"2018-06-03T07:25\",                \"origin\": {                  \"airport\": \"PEN\"                },                \"destination\": {                  \"airport\": \"KUL\",                  \"terminal\": \"M\"                },                \"marketing_airline\": \"OD\",                \"operating_airline\": \"OD\",                \"flight_number\": \"2105\",                \"aircraft\": \"738\",                \"booking_info\": {                  \"travel_class\": \"ECONOMY\",                  \"booking_code\": \"Q\",                  \"seats_remaining\": 9                }              }            ]          },          \"inbound\": {            \"flights\": [              {                \"departs_at\": \"2018-06-04T14:10\",                \"arrives_at\": \"2018-06-04T15:10\",                \"origin\": {                  \"airport\": \"KUL\",                  \"terminal\": \"M\"                },                \"destination\": {                  \"airport\": \"PEN\"                },                \"marketing_airline\": \"OD\",                \"operating_airline\": \"OD\",                \"flight_number\": \"2108\",                \"aircraft\": \"739\",                \"booking_info\": {                  \"travel_class\": \"ECONOMY\",                  \"booking_code\": \"O\",                  \"seats_remaining\": 5                }              }            ]          }        }      ],      \"fare\": {        \"total_price\": \"360.00\",        \"price_per_adult\": {          \"total_fare\": \"360.00\",          \"tax\": \"104.00\"        },        \"restrictions\": {          \"refundable\": false,          \"change_penalties\": true        }      }    }  ]}";
 RootObject travelInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(json);

Для получения всех bookingInfo в ответе json.

        foreach(Result result in travelInfo.results)
        {
            foreach(Itinerary itn in travelInfo.results[0].itineraries)
            {
                //For Inbound Flights
                foreach (Flight2 fl2 in itn.inbound.flights)
                {
                    Console.WriteLine("BookingCode:"+fl2.booking_info.booking_code);
                    Console.WriteLine("Seats Remaining:" + fl2.booking_info.seats_remaining);
                    Console.WriteLine("Travel Class:" + fl2.booking_info.travel_class);
                }
                //For Outbound Flights
                foreach(Flight fl1 in itn.outbound.flights)
                {
                    Console.WriteLine("BookingCode:" + fl1.booking_info.booking_code);
                    Console.WriteLine("Seats Remaining:" + fl1.booking_info.seats_remaining);
                    Console.WriteLine("Travel Class:" + fl1.booking_info.travel_class);
                }
            }
        }

Вывод:

Код бронирования: Осталось мест: 5 Класс путешествия: ЭКОНОМИКА Код бронирования: Осталось мест: Q Класс путешествия: ЭКОНОМИКА

0 голосов
/ 02 июня 2018

Используйте эту модель C # для вашего json из эту ссылку

namespace Flighting
{
    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class Flight
    {
        [JsonProperty("currency")]
        public string Currency { get; set; }

        [JsonProperty("results")]
        public List<Result> Results { get; set; }
    }

    public partial class Result
    {
        [JsonProperty("itineraries")]
        public List<Itinerary> Itineraries { get; set; }

        [JsonProperty("fare")]
        public Fare Fare { get; set; }
    }

    public partial class Fare
    {
        [JsonProperty("total_price")]
        public string TotalPrice { get; set; }

        [JsonProperty("price_per_adult")]
        public PricePerAdult PricePerAdult { get; set; }

        [JsonProperty("restrictions")]
        public Restrictions Restrictions { get; set; }
    }

    public partial class PricePerAdult
    {
        [JsonProperty("total_fare")]
        public string TotalFare { get; set; }

        [JsonProperty("tax")]
        public string Tax { get; set; }
    }

    public partial class Restrictions
    {
        [JsonProperty("refundable")]
        public bool Refundable { get; set; }

        [JsonProperty("change_penalties")]
        public bool ChangePenalties { get; set; }
    }

    public partial class Itinerary
    {
        [JsonProperty("outbound")]
        public Outbound Outbound { get; set; }

        [JsonProperty("inbound")]
        public Inbound Inbound { get; set; }
    }

    public partial class Inbound
    {
        [JsonProperty("flights")]
        public List<InboundFlight> Flights { get; set; }
    }

    public partial class InboundFlight
    {
        [JsonProperty("departs_at")]
        public string DepartsAt { get; set; }

        [JsonProperty("arrives_at")]
        public string ArrivesAt { get; set; }

        [JsonProperty("origin")]
        public Origin Origin { get; set; }

        [JsonProperty("destination")]
        public Destination Destination { get; set; }

        [JsonProperty("marketing_airline")]
        public string MarketingAirline { get; set; }

        [JsonProperty("operating_airline")]
        public string OperatingAirline { get; set; }

        [JsonProperty("flight_number")]
        public string FlightNumber { get; set; }

        [JsonProperty("aircraft")]
        public string Aircraft { get; set; }

        [JsonProperty("booking_info")]
        public BookingInfo BookingInfo { get; set; }
    }

    public partial class BookingInfo
    {
        [JsonProperty("travel_class")]
        public string TravelClass { get; set; }

        [JsonProperty("booking_code")]
        public string BookingCode { get; set; }

        [JsonProperty("seats_remaining")]
        public long SeatsRemaining { get; set; }
    }

    public partial class Destination
    {
        [JsonProperty("airport")]
        public string Airport { get; set; }
    }

    public partial class Origin
    {
        [JsonProperty("airport")]
        public string Airport { get; set; }

        [JsonProperty("terminal")]
        public string Terminal { get; set; }
    }

    public partial class Outbound
    {
        [JsonProperty("flights")]
        public List<OutboundFlight> Flights { get; set; }
    }

    public partial class OutboundFlight
    {
        [JsonProperty("departs_at")]
        public string DepartsAt { get; set; }

        [JsonProperty("arrives_at")]
        public string ArrivesAt { get; set; }

        [JsonProperty("origin")]
        public Destination Origin { get; set; }

        [JsonProperty("destination")]
        public Origin Destination { get; set; }

        [JsonProperty("marketing_airline")]
        public string MarketingAirline { get; set; }

        [JsonProperty("operating_airline")]
        public string OperatingAirline { get; set; }

        [JsonProperty("flight_number")]
        public string FlightNumber { get; set; }

        [JsonProperty("aircraft")]
        public string Aircraft { get; set; }

        [JsonProperty("booking_info")]
        public BookingInfo BookingInfo { get; set; }
    }

    public partial class Flight
    {
        public static Flight FromJson(string json) => JsonConvert.DeserializeObject<Flight>(json, Flighting.Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this Flight self) => JsonConvert.SerializeObject(self, Flighting.Converter.Settings);
    }

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters = {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }
}

Затем используйте это в своем классе

var flight = Flighting.Flight.FromJson(yourjson);

         string currency   =   flight.Currency;
            var restrictions = flight.Results[0].Fare.Restrictions;
            var totalprice = flight.Results[0].Fare.TotalPrice;
            var adult = flight.Results[0].Fare.PricePerAdult;
            var a = flight.Results[0].Itineraries[0].Inbound.Flights[0].Aircraft;
            var bookingInfo = flight.Results[0].Itineraries[0].Inbound.Flights[0].BookingInfo;
            var d = flight.Results[0].Itineraries[0].Inbound.Flights[0].DepartsAt;
            var f = flight.Results[0].Itineraries[0].Inbound.Flights[0].FlightNumber;
            var op = flight.Results[0].Itineraries[0].Inbound.Flights[0].OperatingAirline;

Зацикливание, я использовал нулевой индексдля теста

...