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
+ "¤cy=" + 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
Related
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
{
}
I want to create the following JSON object string using C#. I am getting data from the database to set the data.
{
"markers":[
{
"articles":[
{
"ID":3759,
"post_type":"report",
"post_title":"No",
"post_url":"/report/",
"fields":[
{
"institution_name":"Georgetown"
},
{
"journal_name":"Jama"
},
{
"lead_author":{
"id":2214,
"name":"Kelly",
"slug":"dr",
"description":"director",
"image_object":{
"thumbnail":"test.png",
"thumbnail-width":150,
"thumbnail-height":150,
"medium":"test.png",
"medium-width":300,
"medium-height":300,
"medium_large":"test.png",
"medium_large-width":361,
"medium_large-height":361,
"large":"test.png",
"large-width":361,
"large-height":361
}
}
}
]
}
],
"location":{
"name":"location",
"include_on_map":true,
"address":null,
"lat":null,
"lng":null
}
},
{
"articles":[
{
"ID":1893,
"post_type":"report",
"post_title":"Controls",
"post_url":"/report/",
"fields":[
{
"institution_name":"System"
},
{
"journal_name":"World"
},
{
"lead_author":{
"id":1019,
"name":"Hardesty",
"slug":"hardesty",
"description":"",
"image_object":{
}
}
}
]
}
],
"location":{
"name":"location",
"include_on_map":true,
"address":"USA",
"lat":"38.12345",
"lng":"-70.12345"
}
}
],
"params":{
"path":"",
"raw_path":null,
"page":1,
"lang":"en",
"items":9,
"type":"",
"term":null,
"offset":0,
"direction":"DESC",
"order":"date",
"currentpagenumber":[
""
]
}
}
Could you please help me to create the json output using foreach loop?
Below is the code i am having currently.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JSON
{
class Program
{
static void Main(string[] args)
{
string jsonString = string.Empty;
Root root = new Root()
{
Markers = new List<Marker>
{
new Marker()
{
Articles = new List<Article>
{
new Article()
{
ID=1234,
PostTitle="Test",
}
},
Location = new Location()
{
Name="Location" ,
Address="USA",
}
}
},
Params = new Params()
{
Page = 1,
}
};
jsonString = JsonString(root);
Console.WriteLine(jsonString);
Console.ReadLine();
}
public static string JsonString(Root model)
{
string jsonString = JsonConvert.SerializeObject(model);
return jsonString;
}
}
}
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JSON
{
class JsonModel
{
}
public class ImageObject
{
[JsonProperty("thumbnail")]
public string Thumbnail { get; set; }
[JsonProperty("thumbnail-width")]
public int ThumbnailWidth { get; set; }
[JsonProperty("thumbnail-height")]
public int ThumbnailHeight { get; set; }
[JsonProperty("medium")]
public string Medium { get; set; }
[JsonProperty("medium-width")]
public int MediumWidth { get; set; }
[JsonProperty("medium-height")]
public int MediumHeight { get; set; }
[JsonProperty("medium_large")]
public string MediumLarge { get; set; }
[JsonProperty("medium_large-width")]
public int MediumLargeWidth { get; set; }
[JsonProperty("medium_large-height")]
public int MediumLargeHeight { get; set; }
[JsonProperty("large")]
public string Large { get; set; }
[JsonProperty("large-width")]
public int LargeWidth { get; set; }
[JsonProperty("large-height")]
public int LargeHeight { get; set; }
}
public class LeadAuthor
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("slug")]
public string Slug { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("image_object")]
public ImageObject ImageObject { get; set; }
}
public class Field
{
[JsonProperty("institution_name")]
public string InstitutionName { get; set; }
[JsonProperty("journal_name")]
public string JournalName { get; set; }
[JsonProperty("lead_author")]
public LeadAuthor LeadAuthor { get; set; }
}
public class Article
{
[JsonProperty("ID")]
public int ID { get; set; }
[JsonProperty("post_type")]
public string PostType { get; set; }
[JsonProperty("post_title")]
public string PostTitle { get; set; }
[JsonProperty("post_url")]
public string PostUrl { get; set; }
[JsonProperty("fields")]
public List<Field> Fields { get; set; }
}
public class Location
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("include_on_map")]
public bool IncludeOnMap { get; set; }
[JsonProperty("address")]
public string Address { get; set; }
[JsonProperty("lat")]
public string Lat { get; set; }
[JsonProperty("lng")]
public string Lng { get; set; }
}
public class Marker
{
[JsonProperty("articles")]
public List<Article> Articles { get; set; }
[JsonProperty("location")]
public Location Location { get; set; }
}
public class Params
{
[JsonProperty("path")]
public string Path { get; set; }
[JsonProperty("raw_path")]
public object RawPath { get; set; }
[JsonProperty("page")]
public int Page { get; set; }
[JsonProperty("lang")]
public string Lang { get; set; }
[JsonProperty("items")]
public int Items { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("term")]
public object Term { get; set; }
[JsonProperty("offset")]
public int Offset { get; set; }
[JsonProperty("direction")]
public string Direction { get; set; }
[JsonProperty("order")]
public string Order { get; set; }
[JsonProperty("currentpagenumber")]
public List<string> Currentpagenumber { get; set; }
}
public class Root
{
[JsonProperty("markers")]
public List<Marker> Markers { get; set; }
[JsonProperty("params")]
public Params Params { get; set; }
}
}
I have an API call using SmartyAddress, here is the result returned from the API call:
[
{
"input_index": 0,
"candidate_index": 0,
"delivery_line_1": "xx",
"last_line": "xx",
"delivery_point_barcode": "xx",
"components": {
"primary_number": "xx",
"street_name": "xx",
"street_suffix": "xx",
"city_name": "xx",
"state_abbreviation": "xx",
"zipcode": "xx",
"plus4_code": "xx",
"delivery_point": "xx",
"delivery_point_check_digit": "xx"
},
"metadata": {
"record_type": "S",
"zip_type": "Standard",
"county_fips": "36047",
"county_name": "Kings",
"carrier_route": "C009",
"congressional_district": "11",
"rdi": "Residential",
"elot_sequence": "0070",
"elot_sort": "A",
"latitude": 40.6223,
"longitude": -74.00717,
"precision": "Zip9",
"time_zone": "Eastern",
"utc_offset": -5,
"dst": true
},
"analysis": {
"dpv_match_code": "Y",
"dpv_footnotes": "AABB",
"dpv_cmra": "N",
"dpv_vacant": "N",
"active": "Y"
}
}
]
Now I would like to use JSON to return this result especially the analysis component, and here is the code I tried to write, but it always gives me the error:cannot deserialize the current json object into type 'system.collections.generic.list and the following is the code:
public void Main()
{
try
{
var results = Client.Lookup(Dts.Variables["User::authID"].Value.ToString(), Dts.Variables["User::ServiceAddress"].Value.ToString(), Dts.Variables["User::ServiceCity"].Value.ToString(), Dts.Variables["User::ServiceState"].Value.ToString(), Dts.Variables["User::ServiceZipCode"].Value.ToString());
if (results == null)
{
throw new Exception("Failed to get DPV for ServiceAddress");
}
else
{
var DPV = results.analysis;
Dts.Variables["User::DPV"].Value = DPV;
}
}
}
catch (Exception ex)
{
Dts.Variables["User::DPV"].Value = "N";
throw ex;
}
Dts.TaskResult = (int)ScriptResults.Success;
}
public class Client
{
public static SmartyStreetsAddressLookup[] Lookup(string authId = null, string street = null, string city = null, string state = null, string zip = null)
{
try
{
using (WebClient web = new WebClient())
{
JsonSerializer serial = new JsonSerializer();
string response = web.DownloadString(new Uri(String.Format(#"https://us-street.api.smartystreets.com/street-address?auth-id={0}&street={1}&city={2}&state={3}&zipcode={4}", authId, street, city, state, zip)));
return JsonConvert.DeserializeObject<SmartyStreetsAddressLookup[]>(response);
}
}
catch (Exception ex)
{
throw ex;
}
}
}
public class SmartyStreetsAddressLookup
{
public String[] metadata { get; set; }
public String[] analysis { get; set; }
}
Based on your exception message and your code the problem is that you are trying to deserialize a complex object from json into 2 string arrays, those 2 are clearly not compatible. You should be using a complex type that matches what you have in your json. To get a head start on this you can try http://json2csharp.com/, enter your json, and then use the output as a starting point for your c# class structure that then matches your json.
The output of your current json in that site is this.
public class Components
{
public string primary_number { get; set; }
public string street_name { get; set; }
public string street_suffix { get; set; }
public string city_name { get; set; }
public string state_abbreviation { get; set; }
public string zipcode { get; set; }
public string plus4_code { get; set; }
public string delivery_point { get; set; }
public string delivery_point_check_digit { get; set; }
}
public class Metadata
{
public string record_type { get; set; }
public string zip_type { get; set; }
public string county_fips { get; set; }
public string county_name { get; set; }
public string carrier_route { get; set; }
public string congressional_district { get; set; }
public string rdi { get; set; }
public string elot_sequence { get; set; }
public string elot_sort { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
public string precision { get; set; }
public string time_zone { get; set; }
public int utc_offset { get; set; }
public bool dst { get; set; }
}
public class Analysis
{
public string dpv_match_code { get; set; }
public string dpv_footnotes { get; set; }
public string dpv_cmra { get; set; }
public string dpv_vacant { get; set; }
public string active { get; set; }
}
public class RootObject
{
public int input_index { get; set; }
public int candidate_index { get; set; }
public string delivery_line_1 { get; set; }
public string last_line { get; set; }
public string delivery_point_barcode { get; set; }
public Components components { get; set; }
public Metadata metadata { get; set; }
public Analysis analysis { get; set; }
}
You can then deserialize your json into this structure.
return JsonConvert.DeserializeObject<RootObject[]>(response);
Your SmartyStreetsAddressLookup class is incorrect, and does not accurately match the JSON data. metadata and analysis should not be string arrays, but rather their own objects (classes) with the properties that they contain. Try adding the following to your project:
public class Metadata
{
public string record_type { get; set; }
public string zip_type { get; set; }
public string county_fips { get; set; }
public string county_name { get; set; }
public string carrier_route { get; set; }
public string congressional_district { get; set; }
public string rdi { get; set; }
public string elot_sequence { get; set; }
public string elot_sort { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
public string precision { get; set; }
public string time_zone { get; set; }
public int utc_offset { get; set; }
public bool dst { get; set; }
}
public class Analysis
{
public string dpv_match_code { get; set; }
public string dpv_footnotes { get; set; }
public string dpv_cmra { get; set; }
public string dpv_vacant { get; set; }
public string active { get; set; }
}
public class Components
{
public string primary_number { get; set; }
public string street_name { get; set; }
public string street_suffix { get; set; }
public string city_name { get; set; }
public string state_abbreviation { get; set; }
public string zipcode { get; set; }
public string plus4_code { get; set; }
public string delivery_point { get; set; }
public string delivery_point_check_digit { get; set; }
}
And change your SmartyStreetsAddressLookup class to the following:
public class SmartyStreetsAddressLookup
{
public int input_index { get; set; }
public int candidate_index { get; set; }
public string delivery_line_1 { get; set; }
public string last_line { get; set; }
public string delivery_point_barcode { get; set; }
public Components components { get; set; }
public Metadata metadata { get; set; }
public Analysis analysis { get; set; }
}
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);
Lets say i have a string that looks like this
{
"_links": {
"next": "https://api.twitch.tv/kraken/users/test_user1/follows/channels?direction=DESC&limit=25&offset=25",
"self": "https://api.twitch.tv/kraken/users/test_user1/follows/channels?direction=DESC&limit=25&offset=0"
},
"follows": [
{
"created_at": "2013-06-02T09:38:45Z",
"_links": {
"self": "https://api.twitch.tv/kraken/users/test_user1/follows/channels/test_channel"
},
"channel": {
"banner": null,
"_id": 1,
"url": "http://www.twitch.tv/test_channel",
"mature": null,
"teams": [
],
"status": null,
"logo": null,
"name": "test_channel",
"video_banner": null,
"display_name": "test_channel",
"created_at": "2007-05-22T10:37:47Z",
"delay": 0,
"game": null,
"_links": {
"stream_key": "https://api.twitch.tv/kraken/channels/test_channel/stream_key",
"self": "https://api.twitch.tv/kraken/channels/test_channel",
"videos": "https://api.twitch.tv/kraken/channels/test_channel/videos",
"commercial": "https://api.twitch.tv/kraken/channels/test_channel/commercial",
"chat": "https://api.twitch.tv/kraken/chat/test_channel",
"features": "https://api.twitch.tv/kraken/channels/test_channel/features"
},
"updated_at": "2008-02-12T06:04:29Z",
"background": null
}
},
...
]
}
The part in channel is gonna appear x amount of times with the "name" part having a different value. How would I, using regex or not get the value in "name" that in the code above has a value of "test_channel". All times that it appears and then print it to a textbox
The only part I think I've managed is the regex part
string regex = #"(""name"":)\s+(\w+)(,""video_banner"")";
Using Json.Net and this site
var obj = JsonConvert.DeserializeObject<Krysvac.RootObject>(yourJsonString);
foreach(var item in obj.follows)
{
Console.WriteLine(item.channel.name);
}
public class Krysvac
{
public class Links
{
public string next { get; set; }
public string self { get; set; }
}
public class Links2
{
public string self { get; set; }
}
public class Links3
{
public string stream_key { get; set; }
public string self { get; set; }
public string videos { get; set; }
public string commercial { get; set; }
public string chat { get; set; }
public string features { get; set; }
}
public class Channel
{
public object banner { get; set; }
public int _id { get; set; }
public string url { get; set; }
public object mature { get; set; }
public List<object> teams { get; set; }
public object status { get; set; }
public object logo { get; set; }
public string name { get; set; }
public object video_banner { get; set; }
public string display_name { get; set; }
public string created_at { get; set; }
public int delay { get; set; }
public object game { get; set; }
public Links3 _links { get; set; }
public string updated_at { get; set; }
public object background { get; set; }
}
public class Follow
{
public string created_at { get; set; }
public Links2 _links { get; set; }
public Channel channel { get; set; }
}
public class RootObject
{
public Links _links { get; set; }
public List<Follow> follows { get; set; }
}
}
If you don't want to declare these classes, you can use dynamic keyword too
dynamic obj = JsonConvert.DeserializeObject(yourJsonString);
foreach(var item in obj.follows)
{
Console.WriteLine(item.channel.name);
}
If you build classes for your input string like the following using json2csharp.com, you'll get the following classes:
public class Links
{
public string next { get; set; }
public string self { get; set; }
}
public class Links2
{
public string self { get; set; }
}
public class Links3
{
public string stream_key { get; set; }
public string self { get; set; }
public string videos { get; set; }
public string commercial { get; set; }
public string chat { get; set; }
public string features { get; set; }
}
public class Channel
{
public object banner { get; set; }
public int _id { get; set; }
public string url { get; set; }
public object mature { get; set; }
public List<object> teams { get; set; }
public object status { get; set; }
public object logo { get; set; }
public string name { get; set; }
public object video_banner { get; set; }
public string display_name { get; set; }
public string created_at { get; set; }
public int delay { get; set; }
public object game { get; set; }
public Links3 _links { get; set; }
public string updated_at { get; set; }
public object background { get; set; }
}
public class Follow
{
public string created_at { get; set; }
public Links2 _links { get; set; }
public Channel channel { get; set; }
}
public class RootObject
{
public Links _links { get; set; }
public List<Follow> follows { get; set; }
}
Now you just have to deserialize the input json string to RootObject class and fetch all the names in the input string using another utility called Json.net
string json = "JSON STRING";
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
List<string> names = root.follows.Select(follow => follow.channel.name).ToList();
foreach ( string name in names )
{
txtBox += name + "; ";
}
Ok, so i got it working now, however, if i use my username to get back json, i get a huge piece of code that you can view here: https://api.twitch.tv/kraken/users/krysvac/follows/channels
I folllow 31 people but when i use my program on it with the code
using (var w = new WebClient())
{
string json_data = w.DownloadString("https://api.twitch.tv/kraken/users/" + input + "/follows/channels");
dynamic obj = JsonConvert.DeserializeObject(json_data);
foreach (var item in obj.follows)
{
textBox1.AppendText(item.channel.name.ToString() + Environment.NewLine);
}
}
i get 25 out of my 31 people back in the textbox and i dont know why, i tried it on a person that should return more than 100 and got 6 people back.