I am trying to deserialize a json object into c# object and list the Itinerary items.
Here is my json object:
{
"data": {
"Itineraries": [
{
"isDomestic": false,
"departureAirport": "IKA",
"arrivalAirport": "IST"
},
{
"isDomestic": false,
"departureAirport": "IST",
"arrivalAirport": "LAX"
}
]
}
}
here is my c# classes that I use
public class Data
{
public List<itineraries> itineraries { get; set; } = new List<itineraries>();
}
public class itineraries
{
public bool isDomestic { get; set; }
public string departureAirport { get; set; }
public string arrivalAirport { get; set; }
}
here is the code that I use to deserialize
Data availableData= JsonSerializer.Deserialize<Data>(json);
foreach (var item in availableData.itineraries){
Console.WriteLine($"departureAirport:{item.departureAirport}");
}
But I could not list the itineraries.
try this classes
public class Itinerary
{
public bool isDomestic { get; set; }
public string departureAirport { get; set; }
public string arrivalAirport { get; set; }
}
public class Data
{
public List<Itinerary> Itineraries { get; set; }
}
public class Root
{
public Data data { get; set; }
}
and code
var availableData= JsonSerializer.Deserialize<Root>(json);
foreach (var item in availableData.data.Itineraries)
{
Console.WriteLine($"departureAirport:{item.departureAirport}");
}
first, you have to install Newtonsoft.Json from NuGet Manager then use these classes instead of yours
public class Itinerary
{
public bool isDomestic { get; set; }
public string departureAirport { get; set; }
public string arrivalAirport { get; set; }
}
public class Data
{
public List<Itinerary> Itineraries { get; set; }
}
public class Root
{
public Data data { get; set; }
}
the convert code is
var root = JsonConvert.DeserializeObject<Root>(json);
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.