How to deserialize the neston JSON array? - c#

I am trying to read my nested JSON result and I'm able to read the data from the first array. But not able to read from the remaining.
BELOW IS THE CODE WHICH GIVES THE RESULT FROM THE ORDER NODE
Fiddle: https://dotnetfiddle.net/biXBqd
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Collections;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string json = #"{""orders"": [
{
""orderNumber"": ""12345"",
""orderDate"": ""2022-03-16"",
""status"": ""Completed"",
""state"": ""Completed"",
""description"": """",
""subs"": [
{
""subsNumber"": ""54321"",
""Managed"": null,
""customFields"": {},
""FirstVersion"": null,
""LastVersion"": 1,
""Actions"": [
{
""id"": ""abc"",
""sequence"": 0,
""TDates"": [
{
""Date"": ""2022-03-16""
},
{
""Date"": ""2022-03-16""
},
{
""Date"": ""2022-03-16""
}
]
}
]
}
],
""customFields"": {
""OrderDelivery"": null,
""DateOrderDelivered"": null
}
}
],
""nextPage"": ""/orders?page=4"",
""success"": true
}";
ArrayList profileAry1 = new ArrayList();
JObject jsonparsing1 = JObject.Parse(json);
JObject jsonparsing = JObject.Parse(json);
var token = (JArray)jsonparsing.SelectToken("orders");
List<string> AuthorList = new List<string>();
foreach (orders orders in JsonConvert.DeserializeObject<List<orders>>(token.ToString()))
{
string orderNumber = orders.orderNumber.ToString();
string orderDate = orders.orderDate.ToString();
string status = orders.status.ToString();
string state = orders.state.ToString();
string description = orders.description.ToString();
Console.WriteLine("Order Number: " + orderNumber);
Console.WriteLine("Order Number: " + orderDate);
Console.WriteLine("status: " + status);
Console.WriteLine("status: " + state);
Console.WriteLine("description: " + description);
Console.WriteLine();
}
PocoCourse items = JsonConvert.DeserializeObject<PocoCourse>(json);
Console.WriteLine("success: " + items.Success);
Console.WriteLine("Message: " + items.nextPage);
//Console.WriteLine("Number of Types: " + items.orders.Count);
}
}
public class PocoCourse
{
public bool Success { get; set; }
public string nextPage { get; set; }
public List<orders> orders { get; set; }
}
public class orders
{
public string orderNumber { get; set; }
public DateTime orderDate { get; set; }
public string status { get; set; }
public string state { get; set; }
public string description { get; set; }
public List<subs> subs { get; set; }
}
public class subs
{
[JsonProperty("subs")]
public string subsNumber { get; set; }
public string Managed { get; set; }
public string FirstVersion { get; set; }
public string LastVersion { get; set; }
//public List<subscriptions1> subscriptions { get; set; }
public List<List<object>> Points { get; set; }
}
I want to get the values from subs,Actions and TDates as well which I'm not able to achive.
Can anyone please help on this?

you can use this code to get list of dates for example
Data data=JsonConvert.DeserializeObject<Data>(json);
List<DateTime> dates = data.Orders[0].Subs[0].Actions[0].Dates.Select(d => d.Date ).ToList();
result
2022-03-16
2022-03-16
2022-03-16
or actions
List<Action> actions = data.Orders[0].Subs[0].Actions.ToList();
//or since you have only one
Action action = data.Orders[0].Subs[0].Actions.FirstOrDefault();
result
[
{
"id": "abc",
"sequence": 0,
"TDates": [
{
"Date": "2022-03-16T00:00:00"
},
{
"Date": "2022-03-16T00:00:00"
},
{
"Date": "2022-03-16T00:00:00"
}
]
}
]
or if you need only selected values you can do it without creating any classes. For example you can get list of dates
var jsonParsed= JObject.Parse(json);
List<DateTime> dates = jsonParsed["orders"][0]["subs"][0]["Actions"][0]["TDates"]
.Select(d => (DateTime) d["Date"]).ToList();
classes
public partial class Data
{
[JsonProperty("orders")]
public List<Order> Orders { get; set; }
[JsonProperty("nextPage")]
public string NextPage { get; set; }
[JsonProperty("success")]
public bool Success { get; set; }
}
public partial class Order
{
[JsonProperty("orderNumber")]
public long OrderNumber { get; set; }
[JsonProperty("orderDate")]
public DateTimeOffset OrderDate { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("state")]
public string State { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("subs")]
public List<Sub> Subs { get; set; }
[JsonProperty("customFields")]
public OrderCustomFields CustomFields { get; set; }
}
public partial class OrderCustomFields
{
[JsonProperty("OrderDelivery")]
public object OrderDelivery { get; set; }
[JsonProperty("DateOrderDelivered")]
public object DateOrderDelivered { get; set; }
}
public partial class Sub
{
[JsonProperty("subsNumber")]
public long SubsNumber { get; set; }
[JsonProperty("Managed")]
public object Managed { get; set; }
[JsonProperty("customFields")]
public SubCustomFields CustomFields { get; set; }
[JsonProperty("FirstVersion")]
public object FirstVersion { get; set; }
[JsonProperty("LastVersion")]
public long LastVersion { get; set; }
[JsonProperty("Actions")]
public List<Action> Actions { get; set; }
}
public partial class Action
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("sequence")]
public long Sequence { get; set; }
[JsonProperty("TDates")]
public List<TDate> Dates { get; set; }
}
public partial class TDate
{
[JsonProperty("Date")]
public DateTime Date { get; set; }
}
public partial class SubCustomFields
{
}

Related

Value from deserialized JSON string is 0

I'm trying to get the amount of pieces belonging to a certain Lego set using the Brickset API (https://brickset.com/article/52664/api-version-3-documentation)
When writing the Json string to the console it displays the amount of pieces correct. Howeever after deserializing and then writing only the value of pieces to the console it displays 0. All other properties are also not displayed when written to the console.
Result after writing the Json string to the console
{"status":"success","matches":1,"sets":\[
{
"setID": 31844,
"number": "10293",
"numberVariant": 1,
"name": "Santa's Visit",
"year": 2021,
"theme": "Icons",
"themeGroup": "Model making",
"subtheme": "Winter Village Collection",
"category": "Normal",
"released": true,
"pieces": 1445,
"minifigs": 4,
"image": {
"thumbnailURL": "https://images.brickset.com/sets/small/10293-1.jpg",
"imageURL": "https://images.brickset.com/sets/images/10293-1.jpg"
},
"bricksetURL": "https://brickset.com/sets/10293-1",
"collection": {},
"collections": {
"ownedBy": 9350,
"wantedBy": 2307
},
"LEGOCom": {
"US": {
"retailPrice": 99.99,
"dateFirstAvailable": "2021-09-17T00:00:00Z"
},
"UK": {
"retailPrice": 89.99,
"dateFirstAvailable": "2021-09-17T00:00:00Z"
},
"CA": {
"retailPrice": 139.99,
"dateFirstAvailable": "2021-09-17T00:00:00Z"
},
"DE": {
"retailPrice": 99.99,
"dateFirstAvailable": "2021-09-17T00:00:00Z"
}
},
"rating": 4.3,
"reviewCount": 0,
"packagingType": "Box",
"availability": "LEGO exclusive",
"instructionsCount": 15,
"additionalImageCount": 13,
"ageRange": {
"min": 18
},
"dimensions": {
"height": 28.0,
"width": 47.9,
"depth": 8.7,
"weight": 1.656
},
"barcode": {
"EAN": "5702016914313"
},
"extendedData": {
"tags": \[
"Santa Claus|n",
"18 Plus",
"Baked Goods",
"Bedroom",
"Bird",
"Brick Built Tree",
"Brick Separator",
"Christmas",
"Christmas Tree",
"D2c",
"Fireplace",
"Furniture",
"House",
"Kitchen",
"Light Brick",
"Mail",
"Microscale",
"Musical",
"Rocket",
"Seasonal",
"Winter Village"
\]
},
"lastUpdated": "2022-10-03T08:24:39.49Z"
}
\]}
Main Code
class Program
{
static async Task Main(string[] args)
{
await askSetNumber();
}
private async Task GetPosts(string url)
{
HttpClient client = new HttpClient();
string response = await client.GetStringAsync(url);
Console.WriteLine(response);
var set = JsonConvert.DeserializeObject<Rootobject>(response);
Console.WriteLine(set.pieces);
}
static async Task askSetNumber()
{
Console.WriteLine("Please enter a setnumber: ");
string setNumber = "{'setNumber':'" + Console.ReadLine().ToString() + "-1'}";
string url = "https://brickset.com/api/v3.asmx/getSets?apiKey=[APIKey here]&userHash=&params=" + setNumber;
Console.WriteLine(url);
Program program = new Program();
await program.GetPosts(url);
}
}
I made all classes by Pasting the Json as classes, This is the class of the object I need the data off
public class Rootobject
{
public int setID { get; set; }
public string number { get; set; }
public int numberVariant { get; set; }
public string name { get; set; }
public int year { get; set; }
public string theme { get; set; }
public string themeGroup { get; set; }
public string subtheme { get; set; }
public string category { get; set; }
public bool released { get; set; }
public int pieces { get; set; }
public int minifigs { get; set; }
public Image image { get; set; }
public string bricksetURL { get; set; }
public Collection collection { get; set; }
public Collections collections { get; set; }
public Legocom LEGOCom { get; set; }
public float rating { get; set; }
public int reviewCount { get; set; }
public string packagingType { get; set; }
public string availability { get; set; }
public int instructionsCount { get; set; }
public int additionalImageCount { get; set; }
public Agerange ageRange { get; set; }
public Dimensions dimensions { get; set; }
public Barcode barcode { get; set; }
public Extendeddata extendedData { get; set; }
public DateTime lastUpdated { get; set; }
}
I tried the example from How to get some values from a JSON string in C#? but set.pieces keeps returning 0.
This is my first time trying this kind of stuff, but I am stuck on this part.
Rootobject does not contain the same information as the json string you outputted to the console (it also escapes square brackets for some reason), so you either need to specify the entire object or navigate the json tree to get the value you require.
This is not a particularly good or robust solution, but you could replace the var set portion of you code with:
JsonDocument doc = JsonDocument.Parse(response);
if (!doc.RootElement.TryGetProperty("sets", out JsonElement sets)) return;
foreach(var set in sets.EnumerateArray())
{
if (!set.TryGetProperty("pieces", out JsonElement pieces)) continue;
Console.WriteLine(pieces.GetInt32());
}
(You'll also need using System.Text.Json; rather than the newtonsoft one.)
you have you json at first,since you have some strange "/" chars, after this you have to fix your classes too
json=json.Replace("\\[","[").Replace("\\]","]");
Set set = JsonConvert.DeserializeObject<Set>(json);
public class Set
{
public string status { get; set; }
public int matches { get; set; }
public List<SetItem> sets { get; set; }
}
public class SetItem
{
public int setID { get; set; }
public string number { get; set; }
public int numberVariant { get; set; }
public string name { get; set; }
public int year { get; set; }
public string theme { get; set; }
public string themeGroup { get; set; }
public string subtheme { get; set; }
public string category { get; set; }
public bool released { get; set; }
public int pieces { get; set; }
public int minifigs { get; set; }
public Image image { get; set; }
public string bricksetURL { get; set; }
public Collection collection { get; set; }
public Collections collections { get; set; }
public LEGOCom LEGOCom { get; set; }
public double rating { get; set; }
public int reviewCount { get; set; }
public string packagingType { get; set; }
public string availability { get; set; }
public int instructionsCount { get; set; }
public int additionalImageCount { get; set; }
public AgeRange ageRange { get; set; }
public Dimensions dimensions { get; set; }
public Barcode barcode { get; set; }
public ExtendedData extendedData { get; set; }
public DateTime lastUpdated { get; set; }
}
public class LEGOCom
{
public Country US { get; set; }
public Country UK { get; set; }
public Country CA { get; set; }
public Country DE { get; set; }
}
public class AgeRange
{
public int min { get; set; }
}
public class Barcode
{
public string EAN { get; set; }
}
public class Country
{
public double retailPrice { get; set; }
public DateTime dateFirstAvailable { get; set; }
}
and maybe it make some sense to define LEGOCom as a Dictionary, if you have much more countries
public Dictionary<string,Country> LEGOCom { get; set; }

Null Object-DeSerializing JSON C#

Returned object :
{
"_expands": [],
"size": 3,
"start": 3,
"limit": 3,
"isLastPage": false,
"_links": {
"base": "http://host:port/context/rest/desk",
"context": "context",
"next": "http://host:port/context/rest/desk",
"prev": "http://host:port/context/rest/desk"
},
"values": [
{
"status": "Waiting for Customer",
"statusDate": {
"iso8601": "2015-10-08T14:05:00+0700",
"polaris": "2015-10-08T14:05:00.000+0700",
"friendly": "Today 14:05 PM",
"epochMillis": 1444287900000
}
},
{
"status": "Waiting for Support",
"statusDate": {
"iso8601": "2015-10-08T14:01:00+0700",
"polaris": "2015-10-08T14:01:00.000+0700",
"friendly": "Today 14:01 PM",
"epochMillis": 1444287660000
}
},
{
"status": "Waiting for Customer",
"statusDate": {
"iso8601": "2015-10-08T14:00:00+0700",
"polaris": "2015-10-08T14:00:00.000+0700",
"friendly": "Today 14:00 PM",
"epochMillis": 1444287600000
}
}
]
}
Classes :
public class polarisState
{
public string[] expands { get; set; }
public int size { get; set; }
public int start { get; set; }
public int limit { get; set; }
public bool isLastPage { get; set; }
public _links links { get; set; }
public values[] values { get; set; }
}
public class _links
{
//public string base {get; set;}
public string context { get; set; }
public string next { get; set; }
public string prev { get; set; }
}
public class values
{
public string status { get; set; }
public statusDate statusDate { get; set; }
}
public class statusDate
{
public string iso8601 { get; set; }
public string polaris { get; set; }
public string friendly { get; set; }
public int epochMillis { get; set; }
}
code below :
if (resp2.IsSuccessStatusCode)
{
var values = JsonConvert.DeserializeObject<JiraState>(resp2.Content.ReadAsStringAsync().Result); }
You should change the class polarisState to
public class polarisState
{
public List<string> expands { get; set; }
public int size { get; set; }
public int start { get; set; }
public int limit { get; set; }
public bool isLastPage { get; set; }
public _links links { get; set; }
public List<values> values { get; set; }
}
array to List.
Then change the statusDate to:
public class statusDate
{
public string iso8601 { get; set; }
public string polaris { get; set; }
public string friendly { get; set; }
public long epochMillis { get; set; }
}
change the epochMillis from int to long value type.
It's done.
Use the async method and change the code as follow:
var content = await resp2.Content.ReadAsStringAsync();
var values = JsonConvert.DeserializeObject<polarisState>(content);

Unable to Parsing nested Json file in C#

I have Json format response from a API call and I want to map the data from the response to each varibales.
Json format
{
"success": true,
"data": {
"students": [
{
"Admission_date": "2018-05-01",
"Name": "Sree",
"Branch": "Electronics",
"Semester": "2",
"HOD": "Mahesh",
},
{
"Admission_date": "2018-05-01",
"Name": "Naresh",
"Branch": "Electronics",
"Semester": "2",
"HOD": "Mahesh",
}
],
"remaining": 0
}
}
I have tried to parse the JSON response and then to load the value through for each. But I'm not able to achieve the solution.
JObject jsonparsing1 = JObject.Parse(str4); //str4;- Json value
var token1 = (JArray)jsonparsing1.SelectToken("data");
var token2 = (JArray)jsonparsing1.SelectToken("data[0]Students");
JArray abc = JsonConvert.DeserializeObject<JArray>(token2.ToString());
foreach (var test in abc)
{
String Admission_date=test["Admission_date"];
String Name=test["Name"];
String Branch=test["Branch"];
String Semester=test["Semester"];
String HOD=test["HOD"];
String remaining=test["remaining"];
}
Expected result
String Admission_date=Admission_date
String Name=Name
String Branch=Branch
String Semester=Semester
String HOD=HOD
String remaining=remaining
Could anyone please help me on this?
I think you can use this sample:
public class JsonData
{
public bool success { get; set; }
public Data data { get; set; }
}
public class Data
{
public Data()
{
this.students = new List<Student>();
}
public List<Student> students { get; set; }
public int remaining { get; set; }
}
public class Student
{
public string Admission_date { get; set; }
public string Name { get; set; }
public string Branch { get; set; }
public string Semester { get; set; }
public string HOD { get; set; }
}
And then:
JsonData abc = JsonConvert.DeserializeObject<JsonData>(token2.ToString());
I will do this way!
public class Student
{
public string Admission_date { get; set; }
public string Name { get; set; }
public string Branch { get; set; }
public string Semester { get; set; }
public string HOD { get; set; }
}
public class Data
{
public List<Student> students { get; set; }
public int remaining { get; set; }
}
public class RootObject
{
public bool success { get; set; }
public Data data { get; set; }
}
and in C# Code Just use only below line:
var obj = JsonConvert.DeserializeObject<RootObject>("{ \"success\": true,\"data\": {\"students\": [{ \"Admission_date\": \"2018-05-01\",\"Name\": \"Sree\",\"Branch\":\"Electronics\",\"Semester\": \"2\",\"HOD\": \"Mahesh\",}],\"remaining\": 0}}");
use
foreach(var item in obj.data.students)
{
// Access Admission_date etc.
string name = item.Name;
}
dotnetfiddle

Retrieve Value From Nested Json

I have a Json as below.
{
"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
}
}
}
]
}
And I use the code below to retrieve the value from the Json. I able to retrieve the "departs_at", "arrives_at", "marketing_airline" but I unable to retrieve the value inside "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/>";
}
I wish to ask how possible I can retrieve the value inside the booking_info?
Thanks for every members here that help.
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; }
}
This will work like charm.
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);
For Retrieving all bookingInfo in the json response.
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);
}
}
}
Output:
BookingCode:O
Seats Remaining:5
Travel Class:ECONOMY
BookingCode:Q
Seats Remaining:9
Travel Class:ECONOMY
Use this C# Model for your json from this link
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 }
},
};
}
}
Then use this in your class
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;
Loop appropriately, i used index zero for a test case

Deserialize json multiple array

I have been hitting a wall for days with this.
Can someone please tell me how to deserialize this? I can deserialize single json but deserializing an array has got me stumped.
[
{
"msys": {
"message_event": {
"type": "bounce",
"bounce_class": "1",
"campaign_id": "Example Campaign Name",
"customer_id": "1",
"delv_method": "esmtp",
"device_token": "45c19189783f867973f6e6a5cca60061ffe4fa77c547150563a1192fa9847f8a",
"error_code": "554",
"ip_address": "127.0.0.1",
"message_id": "0e0d94b7-9085-4e3c-ab30-e3f2cd9c273e",
"msg_from": "sender#example.com",
"msg_size": "1337",
"num_retries": "2",
"rcpt_meta": {
"customKey": "customValue"
},
"rcpt_tags": [
"male",
"US"
],
"rcpt_to": "recipient#example.com",
"rcpt_type": "cc",
"raw_reason": "MAIL REFUSED - IP (17.99.99.99) is in black list",
"reason": "MAIL REFUSED - IP (a.b.c.d) is in black list",
"routing_domain": "example.com",
"subject": "Summer deals are here!",
"template_id": "templ-1234",
"template_version": "1",
"timestamp": 1427736822,
"transmission_id": "65832150921904138"
}
}
}
]
My classes are defined as:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public Msys msys { get; set; }
}
public class Msys
{
public Message_Event message_event { get; set; }
}
public class Message_Event
{
public string type { get; set; }
public string bounce_class { get; set; }
public string campaign_id { get; set; }
public string customer_id { get; set; }
public string delv_method { get; set; }
public string device_token { get; set; }
public string error_code { get; set; }
public string ip_address { get; set; }
public string message_id { get; set; }
public string msg_from { get; set; }
public string msg_size { get; set; }
public string num_retries { get; set; }
public Rcpt_Meta rcpt_meta { get; set; }
public string[] rcpt_tags { get; set; }
public string rcpt_to { get; set; }
public string rcpt_type { get; set; }
public string raw_reason { get; set; }
public string reason { get; set; }
public string routing_domain { get; set; }
public string subject { get; set; }
public string template_id { get; set; }
public string template_version { get; set; }
public int timestamp { get; set; }
public string transmission_id { get; set; }
}
public class Rcpt_Meta
{
public string customKey { get; set; }
}
In my case this works. You need to tell Newtonsoft.Json what is your destinationt type (array = list):
var des = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Class1>>(json);
This is a simple complete example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NewtonSoftSample
{
class Program
{
static void Main(string[] args)
{
string json =
#"
[
{
""msys"": {
""message_event"": {
""type"": ""bounce"",
""bounce_class"": ""1"",
""campaign_id"": ""Example Campaign Name"",
""customer_id"": ""1"",
""delv_method"": ""esmtp"",
""device_token"": ""45c19189783f867973f6e6a5cca60061ffe4fa77c547150563a1192fa9847f8a"",
""error_code"": ""554"",
""ip_address"": ""127.0.0.1"",
""message_id"": ""0e0d94b7-9085-4e3c-ab30-e3f2cd9c273e"",
""msg_from"": ""sender#example.com"",
""msg_size"": ""1337"",
""num_retries"": ""2"",
""rcpt_meta"": {
""customKey"": ""customValue""
},
""rcpt_tags"": [
""male"",
""US""
],
""rcpt_to"": ""recipient#example.com"",
""rcpt_type"": ""cc"",
""raw_reason"": ""MAIL REFUSED - IP (17.99.99.99) is in black list"",
""reason"": ""MAIL REFUSED - IP (a.b.c.d) is in black list"",
""routing_domain"": ""example.com"",
""subject"": ""Summer deals are here!"",
""template_id"": ""templ-1234"",
""template_version"": ""1"",
""timestamp"": 1427736822,
""transmission_id"": ""65832150921904138""
}
}
}
]
";
var des = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Class1>>(json);
Console.WriteLine("Done");
Console.ReadLine();
}
}
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public Msys msys { get; set; }
}
public class Msys
{
public Message_Event message_event { get; set; }
}
public class Message_Event
{
public string type { get; set; }
public string bounce_class { get; set; }
public string campaign_id { get; set; }
public string customer_id { get; set; }
public string delv_method { get; set; }
public string device_token { get; set; }
public string error_code { get; set; }
public string ip_address { get; set; }
public string message_id { get; set; }
public string msg_from { get; set; }
public string msg_size { get; set; }
public string num_retries { get; set; }
public Rcpt_Meta rcpt_meta { get; set; }
public string[] rcpt_tags { get; set; }
public string rcpt_to { get; set; }
public string rcpt_type { get; set; }
public string raw_reason { get; set; }
public string reason { get; set; }
public string routing_domain { get; set; }
public string subject { get; set; }
public string template_id { get; set; }
public string template_version { get; set; }
public int timestamp { get; set; }
public string transmission_id { get; set; }
}
public class Rcpt_Meta
{
public string customKey { get; set; }
}
}
You're coming with the wrong approach. You want to be able not to know what fields the json contains but only that it will be a valid json object that can be parsed.
I'd first recommend you to understand what json object really is and what it can be composed from. You can read it here
Next, you can use this as a json parser.
Documentation about the use can be found here.
Try deserializing to a List<Class1>
var list = JsonConvert.DeserializeObject<List<Class1>>(json);
foreach (Message_Event msg in list.Select(c => c.msys.message_event))
{
Console.WriteLine("campaign: " + msg.campaign_id);
Console.WriteLine("from: " + msg.msg_from);
Console.WriteLine("to: " + msg.rcpt_to);
// etc.
}
Fiddle: https://dotnetfiddle.net/Ei0apw
You can use:
public class Msys
{
public List<Message_Event> message_event { get; set; }
}
And initialize your List<> with
System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Message_Event>(json);

Categories

Resources