Generating multilevel JSON using C# with multiple records - c#

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; }
}
}

Related

Getting a JsonSerializationException when trying to deserialize PlayerStats

I want to insert into my class data from JSON but I got a Newtonsoft.Json.JsonSerializationException.
My PlayerStats class is good, I think, and I don't know why it's not working.
I can download and print JSON to the console but my code stops working at the point when I try to deserialize. I tried to add settings to deserialize but it's still not working.
Here is my code:
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Net;
namespace DiscordBot
{
class Osu
{
public string _nickname;
private string _key = "key";
public class PlayerStats
{
[JsonProperty("user_id")]
public int UserId { get; set; }
[JsonProperty("username")]
public string UserName { get; set; }
[JsonProperty("count300")]
public int Count300 { get; set; }
[JsonProperty("count100")]
public int Count100 { get; set; }
[JsonProperty("count50")]
public int Count50 { get; set; }
[JsonProperty("playcount")]
public int PlayCount { get; set; }
[JsonProperty("ranked_score")]
public long RankedScore { get; set; }
[JsonProperty("total_score")]
public long TotalScore { get; set; }
[JsonProperty("pp_rank")]
public int PpRank { get; set; }
[JsonProperty("level")]
public double Level { get; set; }
[JsonProperty("pp_raw")]
public double RawPp { get; set; }
[JsonProperty("accuracy")]
public double Accuracy { get; set; }
[JsonProperty("count_rank_ss")]
public int CountRankSs { get; set; }
[JsonProperty("count_rank_ssh")]
public int CoundRankSsh { get; set; }
[JsonProperty("count_rank_s")]
public int CountRankS { get; set; }
[JsonProperty("count_rank_sh")]
public int CountRankSh { get; set; }
[JsonProperty("count_rank_a")]
public int CountRankA { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("pp_country_rank")]
public int PpCountryRank { get; set; }
}
public PlayerStats GetUserStats()
{
string json = string.Empty;
var result = JsonConvert.DeserializeObject<PlayerStats>(json);
try
{
string url = #"https://osu.ppy.sh/api/get_user";
using (WebClient wc = new WebClient())
{
wc.QueryString.Add("k", _key);
wc.QueryString.Add("u", _nickname);
wc.QueryString.Add("m", "0");
json = wc.DownloadString(url);
Console.WriteLine(json);
result = JsonConvert.DeserializeObject<PlayerStats>(json);
return result;
}
}
catch (WebException ex)
{
Console.WriteLine("Osu Error: " + ex.Status);
}
return result;
}
}
}
JSON:
[
{
"user_id":"10415972"
,"username":"iGruby"
,"count300":"851431"
,"count100":"15449 6"
,"count50":"19825"
,"playcount":"7129"
,"ranked_score":"453511877"
,"total_score" :"2735863526"
,"pp_rank":"147461"
,"level":"74.5611"
,"pp_raw":"1642.73"
,"accuracy" :"94.46521759033203"
,"count_rank_ss":"13"
,"count_rank_ssh":"2"
,"count_rank_s":"3 6"
,"count_rank_sh":"13"
,"count_rank_a":"65"
,"country":"PL"
,"pp_country_rank":"77 20"
,"events":[]
}
]
Refer this Tested Answer from the file I have loaded your json and DeserializeObject check my model also and how I am DeserializeObject
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string data = File.ReadAllText("D://readjson.txt");
var obj = JsonConvert.DeserializeObject<List<RootObject>>(data);
}
}
public class RootObject
{
public string user_id { get; set; }
public string username { get; set; }
public string count300 { get; set; }
public string count100 { get; set; }
public string count50 { get; set; }
public string playcount { get; set; }
public string ranked_score { get; set; }
public string total_score { get; set; }
public string pp_rank { get; set; }
public string level { get; set; }
public string pp_raw { get; set; }
public string accuracy { get; set; }
public string count_rank_ss { get; set; }
public string count_rank_ssh { get; set; }
public string count_rank_s { get; set; }
public string count_rank_sh { get; set; }
public string count_rank_a { get; set; }
public string country { get; set; }
public string pp_country_rank { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<object> events { get; set; }
}
}
Pp_country_rank and count_rank_s contains a space. This is trying to be parsed to an integer.
"count_rank_s":"3 6"
,"count_rank_sh":"13"
,"count_rank_a":"65"
,"country":"PL"
,"pp_country_rank":"77 20"

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

c# convert nested sub classes to json

I am trying to (serialise?) a class in to JSON and am getting a null reference exception - please can you help me understand why and possible fix this?
I wrote a class which contains several nested classes (the JSON structure was provided by the UK carrier DPD).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DPDJSONLibrary
{
public class DPD_JSON
{
// insert shipment request
/// <summary>
/// Root Object. Insert Shipment Request
/// </summary>
public class IS
{
public string job_id { get; set; }
public bool collectionOnDelivery { get; set; }
public IS_Invoice invoice { get; set; }
public string collectionDate { get; set; }
public bool consolidate { get; set; }
public IS_Consignment consignment { get; set; }
}
public class IS_Address
{
public string addressId { get; set; }
public string countryCode { get; set; }
public string countryName { get; set; }
public string county { get; set; }
public string locality { get; set; }
public string organisation { get; set; }
public string postcode { get; set; }
public string street { get; set; }
public string town { get; set; }
}
public class IS_ContactDetails
{
public string contactName { get; set; }
public string telephone { get; set; }
}
public class IS_PickupLocation
{
public IS_Address address { get; set; }
public bool allowRemotePickup { get; set; }
public string pickupLocationCode { get; set; }
}
public class IS_NotificationDetails
{
public string email { get; set; }
public string mobile { get; set; }
}
public class IS_ParcelProduct
{
public string countryOfOrigin { get; set; }
public Int32 numberOfItems { get; set; }
public string productCode { get; set; }
public string productFabricContent { get; set; }
public string productHarmonisedCode { get; set; }
public string productItemsDescription { get; set; }
public string productTypeDescription { get; set; }
public decimal unitValue { get; set; }
public decimal unitWeight { get; set; }
}
public class IS_InvoiceItem
{
public string countryOfOrigin { get; set; }
public string itemCode { get; set; }
public string itemDescription { get; set; }
public int numberOfItems { get; set; }
public decimal unitValue { get; set; }
}
public class IS_InvoiceBillingDetails
{
public IS_Address address { get; set; }
public IS_ContactDetails contactDetails { get; set; }
public string vatNumber { get; set; }
}
public class IS_Invoice
{
public string countryOfOrigin { get; set; }
public IS_InvoiceBillingDetails invoiceBillingDetails { get; set; }
public string invoiceCustomsNumber { get; set; }
public string invoiceExportReason { get; set; }
public bool invoiceIsDeclared { get; set; }
public IS_InvoiceItem invoiceItem { get; set; }
public string invoiceTermsOfDelivery { get; set; }
public int invoiceType { get; set; }
public int totalItems { get; set; }
public decimal totalValue { get; set; }
public decimal totalWeight { get; set; }
}
public class IS_DeliveryDetails
{
public IS_Address address { get; set; }
public IS_ContactDetails contactDetails { get; set; }
public IS_NotificationDetails notificationDetails { get; set; }
public IS_PickupLocation deliveryDetails { get; set; }
}
public class IS_CollectionDetails
{
public IS_Address address { get; set; }
public IS_ContactDetails contactDetails { get; set; }
}
public class IS_Parcels
{
public bool isVoided { get; set; }
public string labelNumber { get; set; }
public int packageNumber { get; set; }
public string parcelNumber { get; set; }
public IS_ParcelProduct parcelProduct { get; set; }
public string parcelnetBarcode { get; set; }
public string parcelnetData { get; set; }
public string parcelnetLabelNumber { get; set; }
}
public class IS_Consignment
{
public IS_CollectionDetails collectionDetails { get; set; }
public string consignmentNumber { get; set; }
public string consignmentRef { get; set; }
public decimal? customsValue { get; set; }
public IS_DeliveryDetails deliveryDetails { get; set; }
public string deliveryInstructions { get; set; }
public bool liability { get; set; }
public decimal liabilityValue { get; set; }
public string networkCode { get; set; }
public int numberOfParcels { get; set; }
public IS_Parcels parcel { get; set; }
public string parceldescription { get; set; }
public string shippingRef1 { get; set; }
public string shippingRef2 { get; set; }
public string shippingRef3 { get; set; }
public decimal totalWeight { get; set; }
}
}
}
I have another class containing public variables which I assign values to from code, and a method/function to instantiate my JSON class and pull in the values from the public variables.
I am getting a null reference exception on the line:
NewShipmentObject.consignment.consignmentNumber = null;
The error reads:
error System.NullReferenceException: Object reference not set to an instance of an object
The method I cam calling and getting the error in is below:
using System;
using System.Text;
using System.Net;
// include
using System.IO;
using System.Web.UI.WebControls;
using DPDJSONLibrary;
using System.Web;
using Newtonsoft.Json;
namespace DPDAPILibrary
{
public class DPD_API
{
#region public class variables
public string BusinessUnit;
public string DeliveryDirection;
public string NumberOfParcels;
public string ShipmentType;
public string TotalWeight;
public string CollectionDate;
public string ColName;
public string ColPhone;
public string ColOrganisation;
public string ColCountryCode;
public string ColPostCode;
public string ColStreet;
public string ColLocality;
public string ColTown;
public string ColCounty;
public string DelName;
public string DelPhone;
public string DelOrganisation;
public string DelCountryCode;
public string DelPostcode;
public string DelStreet;
public string DelLocality;
public string DelTown;
public string DelCounty;
public string DelNotificationEmail;
public string DelNotificationMobile;
public string NetworkCode;
public string ShippingRef1;
public string ShippingRef2;
public string ShippingRef3;
public string CustomsValue;
public string DeliveryInstructions;
public string ParcelDescription;
public string LiabilityValue;
public string Liability;
#endregion
public Boolean insertShipment(out string JSONData)
{
try
{
DPD_JSON.IS NewShipmentObject = new DPD_JSON.IS();
NewShipmentObject.job_id = null;
NewShipmentObject.collectionOnDelivery = false;
NewShipmentObject.invoice = null;
NewShipmentObject.collectionDate = CollectionDate;
NewShipmentObject.consolidate = false;
NewShipmentObject.consignment.consignmentNumber = null;
NewShipmentObject.consignment.consignmentRef = null;
NewShipmentObject.consignment.parcel = null;
NewShipmentObject.consignment.collectionDetails.contactDetails.contactName = ColName;
NewShipmentObject.consignment.collectionDetails.contactDetails.telephone = ColPhone;
NewShipmentObject.consignment.collectionDetails.address.organisation = ColOrganisation;
NewShipmentObject.consignment.collectionDetails.address.countryCode = ColCountryCode;
NewShipmentObject.consignment.collectionDetails.address.postcode = ColPostCode;
NewShipmentObject.consignment.collectionDetails.address.street = ColStreet;
NewShipmentObject.consignment.collectionDetails.address.locality = ColLocality;
NewShipmentObject.consignment.collectionDetails.address.town = ColTown;
NewShipmentObject.consignment.collectionDetails.address.county = ColCounty;
NewShipmentObject.consignment.deliveryDetails.contactDetails.contactName = ColName;
NewShipmentObject.consignment.deliveryDetails.contactDetails.telephone = DelPhone;
NewShipmentObject.consignment.deliveryDetails.address.organisation = DelOrganisation;
NewShipmentObject.consignment.deliveryDetails.address.countryCode = DelCountryCode;
NewShipmentObject.consignment.deliveryDetails.address.postcode = DelPostcode;
NewShipmentObject.consignment.deliveryDetails.address.street = DelStreet;
NewShipmentObject.consignment.deliveryDetails.address.locality = DelLocality;
NewShipmentObject.consignment.deliveryDetails.address.town = DelTown;
NewShipmentObject.consignment.deliveryDetails.address.county = DelCounty;
NewShipmentObject.consignment.deliveryDetails.notificationDetails.email = DelNotificationEmail;
NewShipmentObject.consignment.deliveryDetails.notificationDetails.mobile = DelNotificationMobile;
// default output value
JSONData = "";
JSONData = Convert.ToString(JsonConvert.SerializeObject(NewShipmentObject));
}
catch (Exception ex)
{
JSONData = Convert.ToString(ex);
return false;
}
}
}
}
You'll need to initialize all objects (including child entities) before you can use them*, as they will otherwise adopt their default values (which will be null for objects). i.e. replace
NewShipmentObject.consignment.consignmentNumber = null;
with:
NewShipmentObject.consignment = new IS_Consignment();
NewShipmentObject.consignment.consignmentNumber = null;
You can save yourself a lot of typing - instead of line-by-line setting of each field, you can do so using Object Initializer Syntax:
var NewShipmentObject = new DPD_JSON.IS
{
job_id = null,
collectionOnDelivery = false,
consignment = new IS_Consignment
{
consignmentNumber = null,
... more consignment settings here
}
... etc.
It should be noted that you don't need to explicitly set uninitialized variables to their default value, i.e. both
job_id = null,
collectionOnDelivery = false
are redundant, as these should be the default values in any event.
* (unless this initialization is done automatically in the constructor)

Trouble with List (UWP)

I writing app for UWP platform.
I using Binding in code.
Here code for my ViewModel:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Milano.Annotations;
using WooCommerceNET;
using WooCommerceNET.WooCommerce;
using Newtonsoft.Json;
namespace Milano.Classes
{
public class InWorkViewModel: INotifyPropertyChanged
{
private List<LineItem> productList;
public List<LineItem> ProductList
{
get { return productList; }
set { productList = value; OnPropertyChanged(); }
}
private List<RootObject> ordersList;
public List<RootObject> OrdersList
{
get { return ordersList; }
set { ordersList = value; OnPropertyChanged(); }
}
private RootObject ordersChange;
public RootObject OrdersChange
{
get { return ordersChange; }
set { ordersChange = value; OnPropertyChanged(); }
}
private LineItem ordersChange2;
public LineItem OrdersChange2
{
get { return ordersChange2; }
set { ordersChange2 = value;OnPropertyChanged(); }
}
public InWorkViewModel()
{
Inwork_down();
// var interval = 100000;
//UpdateWithImterwal(interval);
}
/* private async void UpdateWithImterwal(int interval)
{
// OrdersList.Clear();
Inwork_down();
await Task.Delay(interval).ContinueWith(_ => UpdateWithImterwal(interval));
}*/
public async void Inwork_down()
{
RestAPI rest = new RestAPI("http://simplegames.com.ua/wp-json/wc/v1/", "ck_9d64c027d2c5f81b8bed3342eeccc6d337be813d", "cs_60697b1e6cbdeb8d62d19e0765e339f8e3334754");
WCObject wc = new WCObject(rest);
//Get all products
var orders = await wc.GetOrders(new Dictionary<string, string>() {
{ "per_page", "100" }, { "status","processing"} }); // Dodelat filtr dlaya teh chto v rabote
string products = orders.ToFormattedJsonString();
Debug.WriteLine(products);
List<RootObject> rootObjectData = JsonConvert.DeserializeObject<List<RootObject>>(products);
OrdersList = new List<RootObject>(rootObjectData);
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class Billing
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_1 { get; set; }
public string address_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postcode { get; set; }
public string country { get; set; }
public string email { get; set; }
public string phone { get; set; }
}
public class Shipping
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_1 { get; set; }
public string address_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postcode { get; set; }
public string country { get; set; }
}
public class LineItem
{
public int id { get; set; }
public string name { get; set; }
public string sku { get; set; }
public int product_id { get; set; }
public int variation_id { get; set; }
public int quantity { get; set; }
public string tax_class { get; set; }
public double price { get; set; }
public double subtotal { get; set; }
public double subtotal_tax { get; set; }
public double total { get; set; }
public double total_tax { get; set; }
public List<object> taxes { get; set; }
public List<object> meta { get; set; }
}
public class ShippingLine
{
public int id { get; set; }
public string method_title { get; set; }
public string method_id { get; set; }
public double total { get; set; }
public double total_tax { get; set; }
public List<object> taxes { get; set; }
}
public class RootObject
{
public int id { get; set; }
public int parent_id { get; set; }
public string status { get; set; }
public string order_key { get; set; }
public string currency { get; set; }
public string version { get; set; }
public bool prices_include_tax { get; set; }
public string date_created { get; set; }
public string date_modified { get; set; }
public int customer_id { get; set; }
public double discount_total { get; set; }
public double discount_tax { get; set; }
public double shipping_total { get; set; }
public double shipping_tax { get; set; }
public double cart_tax { get; set; }
public double total { get; set; }
public double total_tax { get; set; }
public Billing billing { get; set; }
public Shipping shipping { get; set; }
public string payment_method { get; set; }
public string payment_method_title { get; set; }
public string transaction_id { get; set; }
public string customer_ip_address { get; set; }
public string customer_user_agent { get; set; }
public string created_via { get; set; }
public string customer_note { get; set; }
public string date_completed { get; set; }
public string date_paid { get; set; }
public string cart_hash { get; set; }
public List<LineItem> line_items { get; set; }
public List<object> tax_lines { get; set; }
public List<ShippingLine> shipping_lines { get; set; }
public List<object> fee_lines { get; set; }
public List<object> coupon_lines { get; set; }
}
Where is my problem.
As you see I have this public List<LineItem> line_items { get; set; } in classes. I need to take this list from RootObject and make Binding for values in it like I do for rootObject.
So what is logic of View in app. I BinŠ² some data to Left panel, when I tap element on left panel, I make visible right panel, where I bind properties from public RootObject OrdersChange.
Here is some screens:
How I can do this?
If I understand correctly, you want bind 2 classes to one view. If so, I can suggest 2 ways:
1) Create base class for this 2 classes.
class BaseClass { }
class RootObject: BaseClass { }
class LineItem : BaseClass { }
class MainViewModel
{
public List<LineItem> ProductList { get; set; }
public List<RootObject> OrdersList { get; set; }
public BaseClass LeftListViewSelectedItem { get; set; }
}
2) Or you can set return type of property LeftListViewSelectedItem to object. For binding it's no matter what you return.

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