How to Get Nested Json Values in C#

Accessing Value in Nested JSON with C#

I quite like QuickType.IO for the C# it generates when you paste JSON in:

// <auto-generated />
//
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
// using SomeNamespace;
//
// var authResponse = AuthResponse.FromJson(jsonString);

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

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

public partial class AuthResponse
{
[JsonProperty("Content")]
public Content Content { get; set; }

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

public partial class Content
{
[JsonProperty("Message")]
public string Message { get; set; }
}

public partial class Metadata
{
[JsonProperty("AS2-Properties")]
public As2Properties As2Properties { get; set; }

[JsonProperty("Message-Properties")]
public MessageProperties MessageProperties { get; set; }

[JsonProperty("SL360-Properties")]
public Sl360Properties Sl360Properties { get; set; }
}

public partial class As2Properties
{
[JsonProperty("AS2-AgreementName")]
public object As2AgreementName { get; set; }

[JsonProperty("AS2-FileName")]
public object As2FileName { get; set; }

[JsonProperty("AS2-From")]
public string As2From { get; set; }

[JsonProperty("AS2-IsMDNSent")]
public bool As2IsMdnSent { get; set; }

[JsonProperty("AS2-MDNType")]
public object As2MdnType { get; set; }

[JsonProperty("AS2-MessageID")]
public string As2MessageId { get; set; }

[JsonProperty("AS2-MessageProcessingStatus")]
public object As2MessageProcessingStatus { get; set; }

[JsonProperty("AS2-OutgoingMDN")]
public object As2OutgoingMdn { get; set; }

[JsonProperty("AS2-OutgoingMDNStatus")]
public object As2OutgoingMdnStatus { get; set; }

[JsonProperty("AS2-To")]
public string As2To { get; set; }
}

public partial class MessageProperties
{
[JsonProperty("Blob")]
public object Blob { get; set; }

[JsonProperty("IsMessageInBLOB")]
public bool IsMessageInBlob { get; set; }

[JsonProperty("LogicAppRunID")]
public string LogicAppRunId { get; set; }

[JsonProperty("MessageDate")]
public DateTimeOffset MessageDate { get; set; }

[JsonProperty("MessageID")]
public Guid MessageId { get; set; }

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

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

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

[JsonProperty("SenderIPAddress")]
public string SenderIpAddress { get; set; }
}

public partial class Sl360Properties
{
[JsonProperty("Property1")]
public string Property1 { get; set; }

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

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

public static class Serialize
{
public static string ToJson(this AuthResponse self) => JsonConvert.SerializeObject(self, SomeNamespace.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 }
},
};
}
}

You'd use it like:

        string jsonData = string.Empty;
jsonData = File.ReadAllText(@"D:\code\Projects\AS2ExceptionFunction\ConsoleApp\ConsoleApp\sample.json");

var ar = AuthResponse.FromJson(jsonData);

var messageId = ar.Metadata.MessageProperties.MessageID;

Console.WriteLine(messageId);

Getting data from a deeply nested json object

Try this instead:

IList<JToken> rates = root["HotelListResponse"]["HotelList"]["HotelSummary"][0]["RoomRateDetailsList"]["RoomRateDetails"]["RateInfos"].Children().ToList();

EDIT:

var rateInfo = json["HotelListResponse"]["HotelList"]["HotelSummary"][0]["RoomRateDetailsList"]["RoomRateDetails"]["RateInfos"]["RateInfo"];

var result =JsonConvert.DeserializeObject<RateInfo>( rateInfo .ToString() );

How to get data from a nested json in c#

Thanks for all the response, i was able to solve the task using the SimpleJSON library by Bunny83 GitHub - Bunny83/SimpleJSON: A simple JSON parser in C#

        JSONNode data = JSON.Parse(//jsonData or Url//);
string mId = data["data"]["day2"]["mId"].Value;
string votes = data["data"]["day2"]["votes"].Value;

Read value from nested Json object

MessageId is a string. So you can directly read its value.
Data on the other hand contains objects (see the { and } ). Therefor you need to use

var serial = myJObject.SelectToken("Data.ID.value").Value<String>();

Also see:
Getting 'Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken' when retrieving items from JSON

How do I get nested JSON values in c#?

The following LINQ-to-JSON query should give you the result you are looking for:

Dictionary<string, string> dict = cjob["results"]
.Children<JObject>()
.Select(result => result.SelectToken("metadata.categories").Children<JProperty>()
.Join(result.SelectToken("data.categories").Children<JProperty>(),
metaCat => metaCat.Name,
dataCat => dataCat.Name,
(metaCat, dataCat) => new
{
Name = (string)metaCat.Value["name"],
Value = (string)dataCat.Value
}
)
)
.SelectMany(a => a)
.ToDictionary(a => a.Name, a => a.Value);

foreach (var kvp in dict)
{
Console.WriteLine(kvp.Key + ": " + kvp.Value);
}

This does an inner join between the categories in the metadata object and those in the data object for each result and selects the joined properties into a list (IEnumerable really) of anonymous name-value pairs. The lists of pairs are then flattened down to a single list and finally placed into a dictionary.

I am making the following assumptions about your data:

  • each result object will always have both metadata and data
  • the category names and data values will always be strings
  • the category names will be unique across all results

If these assumptions don't hold you will run into errors and will need to make adjustments to the code.

Here is a working demo: https://dotnetfiddle.net/WkztV5

c# get nested data value from json object

For Json.NET I recommend SelectToken. Please see Querying JSON with SelectToken.

foreach (var element in listkeys) // btw. var/string, not `int`
{
JToken j = o.SelectToken($"$..{element}");
}

Retrieve Value From Nested Json

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



Related Topics



Leave a reply



Submit