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; }
}
Related
Here are my models:
public class Order
{
public IEnumerable<LineItem> LineItems { get; set; }
}
public class LineItem
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("product_id")]
public int ProductId { get; set; }
[JsonPropertyName("variation_id")]
public int VariationId { get; set; }
[JsonPropertyName("quantity")]
public int Quantity { get; set; }
[JsonPropertyName("tax_class")]
public string TaxClass { get; set; }
[JsonPropertyName("subtotal")]
public string Subtotal { get; set; }
[JsonPropertyName("subtotal_tax")]
public string SubtotalTax { get; set; }
[JsonPropertyName("total")]
public string Total { get; set; }
[JsonPropertyName("total_tax")]
public string TotalTax { get; set; }
[JsonPropertyName("taxes")]
public List<object> Taxes { get; set; }
[JsonPropertyName("meta_data")]
public List<MetaData> MetaData { get; set; }
[JsonPropertyName("sku")]
public string Sku { get; set; }
[JsonPropertyName("price")]
public double Price { get; set; }
[JsonPropertyName("parent_name")]
public string ParentName { get; set; }
}
As you can see the HttpRequest property contains an array of line items:
[
{
"id":7928,
"parent_id":0,
"status":"on-hold",
"currency":"GBP",
"version":"5.7.1",
"prices_include_tax":true,
"date_created":"2021-10-04T00:26:22",
"date_modified":"2021-10-04T00:26:22",
"discount_total":"0.00",
"discount_tax":"0.00",
"shipping_total":"0.00",
"shipping_tax":"0.00",
"cart_tax":"0.00",
"total":"2.50",
"total_tax":"0.00",
"customer_id":3,
"order_key":"redacted",
"billing":{
"first_name":"redacted",
"last_name":"redacted",
"company":"",
"address_1":"redacted",
"address_2":"redacted",
"city":"redacted",
"state":"redacted",
"postcode":"redacted",
"country":"GB",
"email":"redacted",
"phone":"redacted"
},
"shipping":{
"first_name":"redacted",
"last_name":"redacted",
"company":"",
"address_1":"redacted",
"address_2":"redacted Lane",
"city":"redacted",
"state":"redacted",
"postcode":"redacted",
"country":"GB",
"phone":""
},
"payment_method":"bacs",
"payment_method_title":"Direct bank transfer",
"transaction_id":"",
"customer_ip_address":"redacted",
"customer_user_agent":"redacted",
"created_via":"redacted",
"customer_note":"",
"date_completed":null,
"date_paid":null,
"cart_hash":"redacted",
"number":"redacted",
"meta_data":[
{
"id":190011,
"key":"redacted",
"value":"no"
},
{
"id":190012,
"key":"redacted",
"value":"yes"
},
{
"id":190016,
"key":"_new_order_email_sent",
"value":"true"
},
{
"id":190017,
"key":"_thankyou_action_done",
"value":"1"
}
],
"line_items":[
{
"id":5287,
"name":"John Guest 3\/8 to 1\/4 Fitting PI0112f4S",
"product_id":5699,
"variation_id":0,
"quantity":1,
"tax_class":"",
"subtotal":"2.50",
"subtotal_tax":"0.00",
"total":"2.50",
"total_tax":"0.00",
"taxes":[
],
"meta_data":[
{
"id":48648,
"key":"_WCPA_order_meta_data",
"value":"",
"display_key":"_WCPA_order_meta_data",
"display_value":""
}
],
"sku":"",
"price":2.5,
"parent_name":null
}
],
"tax_lines":[
],
"shipping_lines":[
{
"id":5288,
"method_title":"Collect from store",
"method_id":"local_pickup",
"instance_id":"13",
"total":"0.00",
"total_tax":"0.00",
"taxes":[
],
"meta_data":[
{
"id":48647,
"key":"Items",
"value":"John Guest 3\/8 to 1\/4 Fitting PI0112f4S × 1",
"display_key":"Items",
"display_value":"John Guest 3\/8 to 1\/4 Fitting PI0112f4S × 1"
}
]
}
],
"fee_lines":[
],
"coupon_lines":[
],
"refunds":[
],
"date_created_gmt":"2021-10-03T23:26:22",
"date_modified_gmt":"2021-10-03T23:26:22",
"date_completed_gmt":null,
"date_paid_gmt":null,
"currency_symbol":"\u00a3",
"_links":{
"self":[
{
"href":"redacted"
}
],
"collection":[
{
"href":"redacted"
}
],
"customer":[
{
"href":"redacted"
}
]
}
},
]
I am wondering why when this is deserialized using
public class WooCommerceOrders
{
private HttpRequestService _httpRequestService;
private string _url;
public WooCommerceOrders()
{
_httpRequestService = new HttpRequestService();
_url = "https://kegthat.com/wp-json/wc/v3/orders";
}
public List<Order> GetOrdersJson()
{
var result = _httpRequestService.CallApi(_url).Content.ReadAsStringAsync();
return _httpRequestService.DeserializeApiResponseJson<List<Order>>(result.Result);
}
}
The json for line items returns
"lineItems": null,
however some fields such as shipping return
"shipping": {
"firstName": null,
"lastName": null,
"company": "",
"address1": null,
"address2": null,
"city": "redacting city",
"state": "Cheshire",
"postcode": "redacting postcode",
"country": "GB",
"phone": ""
},
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
Why can I not return line items?
Try this using Newtonsoft.Json
using Newtonsoft.Json;
.....
public List<Order> GetOrdersJson()
{
var result = _httpRequestService.CallApi(_url).Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject< List<Order>>(result.Result);
}
test to get line_items
var result= GetOrdersJson();
var lineItems=result[0].line_items;
[
{
"id": 5287,
"name": "John Guest 3/8 to 1/4 Fitting PI0112f4S",
"product_id": 5699,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "2.50",
"subtotal_tax": "0.00",
"total": "2.50",
"total_tax": "0.00",
"taxes": [],
"meta_data": [
{
"id": 48648,
"key": "_WCPA_order_meta_data",
"value": "",
"display_key": "_WCPA_order_meta_data",
"display_value": ""
}
],
"sku": "",
"price": 2.5,
"parent_name": null
}
]
classes
public class Order
{
public int id { get; set; }
public int parent_id { get; set; }
public string status { get; set; }
public string currency { get; set; }
public string version { get; set; }
public bool prices_include_tax { get; set; }
public DateTime date_created { get; set; }
public DateTime date_modified { get; set; }
public string discount_total { get; set; }
public string discount_tax { get; set; }
public string shipping_total { get; set; }
public string shipping_tax { get; set; }
public string cart_tax { get; set; }
public string total { get; set; }
public string total_tax { get; set; }
public int customer_id { get; set; }
public string order_key { 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 object date_completed { get; set; }
public object date_paid { get; set; }
public string cart_hash { get; set; }
public string number { get; set; }
public List<MetaData> meta_data { 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; }
public List<object> refunds { get; set; }
public DateTime date_created_gmt { get; set; }
public DateTime date_modified_gmt { get; set; }
public object date_completed_gmt { get; set; }
public object date_paid_gmt { get; set; }
public string currency_symbol { get; set; }
public Links _links { get; set; }
}
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 string phone { get; set; }
}
public class MetaData
{
public int id { get; set; }
public string key { get; set; }
public string value { get; set; }
public string display_key { get; set; }
public string display_value { get; set; }
}
public class LineItem
{
public int id { get; set; }
public string name { 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 string subtotal { get; set; }
public string subtotal_tax { get; set; }
public string total { get; set; }
public string total_tax { get; set; }
public List<object> taxes { get; set; }
public List<MetaData> meta_data { get; set; }
public string sku { get; set; }
public double price { get; set; }
public object parent_name { get; set; }
}
public class ShippingLine
{
public int id { get; set; }
public string method_title { get; set; }
public string method_id { get; set; }
public string instance_id { get; set; }
public string total { get; set; }
public string total_tax { get; set; }
public List<object> taxes { get; set; }
public List<MetaData> meta_data { get; set; }
}
public class Self
{
public string href { get; set; }
}
public class Collection
{
public string href { get; set; }
}
public class Customer
{
public string href { get; set; }
}
public class Links
{
public List<Self> self { get; set; }
public List<Collection> collection { get; set; }
public List<Customer> customer { get; set; }
}
IEnumerable<T> is not a valid type for the serializer. It doesn't define any concrete implementation of a collection for the serializer to parse the JSON into. Use List<T> when deserializing JSON arrays.
public List<Order> GetOrdersJson()
{
var result = _httpRequestService.CallApi(_url).Content.ReadAsStringAsync();
return _httpRequestService.DeserializeApiResponseJson<Order>(result.Result);
}
Deserializing List<Order> which is not the Deserializer is expecting.
Try return _httpRequestService.DeserializeApiResponseJson<Order> instead
I'm having a problem that raises an exception Newtonsoft.Json.JsonSerializationException in Newtonsoft.Json.dll when trying to deserialize an Json formatted string to an user defined object. The string that I'm reading from the file has been written before using the same object.
This is the code of deserielization (exception at the last line).
storageFile = await storageFolder.GetFileAsync(filePath);
string JsonDB = await FileIO.ReadTextAsync(storageFile);
MyDB myDB = Newtonsoft.Json.JsonConvert.DeserializeObject<MyDB>(JsonDB);
Here is the object class (Tag and Astro are enums):
public class MyDB
{
public string Version;
public DateTime Date;
public List<PhotoSpot_v0_1> Lista_v0_1;
}
public enum version
{
v0_1
}
public class PhotoSpot_v0_1
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int Rating { get; set; }
public bool Reminder { get; set; }
public bool Toast { get; set; }
private double Latitude { get; set; }
private double Longitude { get; set; }
private double Altitude { get; set; }
public Geopoint Geopoint { get; set; }
public Geopoint Landmark { get; set; }
public TimeZoneInfo TimeZone { get; set; }
public string MainTag { get; set; }
public version Version { get; set; }
public Landmark_v0_1 Landmarks { get; set; }
public List<Image_v0_1> Images { get; set; }
public List<URL_v0_1> URLs { get; set; }
public List<globalVars.Tag> Tags { get; set; }
public List<Date_v0_1> Dates { get; set; }
public bool Downloaded { get; set; }
public bool Exportable { get; set; }
}
public class Landmark_v0_1
{
public bool freeLandmark { get; set; }
public string Title { get; set; }
private double Latitude { get; set; }
private double Longitude { get; set; }
private double Altitude { get; set; }
public globalVars.Astro Astro { get; set; }
}
public class Image_v0_1
{
public string imageURI { get; set; }
public bool isDownloaded { get; set; }
}
public class URL_v0_1
{
public string sURL { get; set; }
}
public class Tag_v0_1
{
//public string TagName { get; set; }
public globalVars.TagImageURL TagName { get; set; }
}
public class Date_v0_1
{
private double DateStart;
private double DateEnd;
public DateTime DateTimeStart()
{
return CoreTime.JDToDateTime(DateStart);
}
public DateTime DateTimeEnd()
{
return CoreTime.JDToDateTime(DateEnd);
}
public void SetDateTimeStart(DateTime dt)
{
DateStart = CoreTime.DateTimeToJD(dt);
}
public void SetDateTimeEnd(DateTime dt)
{
DateEnd = CoreTime.DateTimeToJD(dt);
}
}
I've checked that the Json string, before writing, after writing and when read are the same. Here it is if it's helpful. If something more is needed I'll post it.
{
"Version": "v0_1",
"Date": "2020-01-08T10:49:04.6992512+01:00",
"Lista_v0_1": [
{
"ID": 2,
"Title": "Abadi gaztelua",
"Description": "",
"Rating": 0,
"Reminder": false,
"Toast": false,
"Geopoint": {
"Position": {
"Latitude": 43.380954170570355,
"Longitude": -1.7520569699123154,
"Altitude": 87.749645113013685
},
"AltitudeReferenceSystem": 2,
"GeoshapeType": 0,
"SpatialReferenceId": 4326
},
"Landmark": null,
"TimeZone": {
"Id": "Romance Standard Time",
"DisplayName": "(UTC+01:00) Brussels, Copenhagen, Madrid, Paris",
"StandardName": "Romance Standard Time",
"DaylightName": "Romance Daylight Time",
"BaseUtcOffset": "01:00:00",
"SupportsDaylightSavingTime": true
},
"MainTag": "Monument",
"Version": 0,
"Landmarks": {
"freeLandmark": false,
"Title": null,
"Astro": 0
},
"Images": [],
"URLs": [],
"Tags": [],
"Dates": [],
"Downloaded": false,
"Exportable": true
}
]
}
I think your class is not proper. I tried your code and it's working.
string filepath = "../../../json.txt";
var test = File.ReadAllText(filepath);
Example myDB = JsonConvert.DeserializeObject<Example>(test);
pl check your following class as per your json
public class Position
{
public double Latitude { get; set; }
public double Longitude { get; set; }
public double Altitude { get; set; }
}
public class Geopoint
{
public Position Position { get; set; }
public int AltitudeReferenceSystem { get; set; }
public int GeoshapeType { get; set; }
public int SpatialReferenceId { get; set; }
}
public class TimeZone
{
public string Id { get; set; }
public string DisplayName { get; set; }
public string StandardName { get; set; }
public string DaylightName { get; set; }
public string BaseUtcOffset { get; set; }
public bool SupportsDaylightSavingTime { get; set; }
}
public class Landmarks
{
public bool freeLandmark { get; set; }
public object Title { get; set; }
public int Astro { get; set; }
}
public class ListaV01
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int Rating { get; set; }
public bool Reminder { get; set; }
public bool Toast { get; set; }
public Geopoint Geopoint { get; set; }
public object Landmark { get; set; }
public TimeZone TimeZone { get; set; }
public string MainTag { get; set; }
public int Version { get; set; }
public Landmarks Landmarks { get; set; }
public IList<object> Images { get; set; }
public IList<object> URLs { get; set; }
public IList<object> Tags { get; set; }
public IList<object> Dates { get; set; }
public bool Downloaded { get; set; }
public bool Exportable { get; set; }
}
public class MyDB
{
public string Version { get; set; }
public DateTime Date { get; set; }
public IList<ListaV01> Lista_v0_1 { get; set; }
}
I am able to deserialise root object but cannot access the underlying classes I receive a null reference exception. I need to extract the fields from the orderitems class.
in the following scenario the derserialization
works great and can extract fields attached to items
var Sresponse = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(Sresponse.items);
However doesn't work here
var Sresponse = JsonConvert.DeserializeObject<Item>(json);
Console.WriteLine(Sresponse.orderitems);
Error message : System.NullReferenceException: Object reference not set to an instance of an object
please help.
Json String
{
"totalcount": 103952,
"items": [
{
"orderid": 113951,
"email": "",
"namefirst": "",
"namelast": "",
"company": "",
"moneyfinal_net": "95.92",
"moneyfinal_vat": "23.98",
"moneytotal_gross_roundoff": "0.00",
"moneytotal_gross_all": "119.90",
"checkouttypename": "Card",
"deliverytypename": "",
"orderdate": 1554836745,
"orderstateid": 10,
"paymentstateid": 20,
"ordertypeid": 10,
"registerid": "{AD16AEE2-235F-318A-4323-6B63EC2C40E7}",
"warehouseid": 18,
"datereserved": null,
"currencycode": "NOK",
"additionaldata": {
"pos-timezone": "Europe/Oslo",
"pos-staff-externalid": "4654"
},
"orderitems": [
{
"orderitemid": 0,
"orderitemtype": 10,
"productid": 5486,
"productname": "Test",
"sku": "320991800016",
"productattributes": "",
"externalinput": "",
"externalinputtitle": "",
"unitlabel": "ST",
"quantity": 1,
"decimalunitquantity": null,
"moneynetpriceperunit": "63.92",
"moneypriceorg": "0.00",
"vatvalue": 25,
"deliveryinfo": "",
"moneyitemtotal_net": "63.92",
"moneyitemtotal_vat": "15.98",
"voucherid": 0,
"vouchercode": "",
"vouchername": "",
"moneyoriginalprice": "63.92",
"moneydiscountedprice": "0.00",
"moneydiscount": "0.00",
"salestaxes": [],
"additionaldata": {},
"decimalquantitytotal": "1.000",
"moneynetpriceperquantity": "63.92"
},
Classes
public class Orderitem
{
public int orderitemid { get; set; }
public int orderitemtype { get; set; }
public int productid { get; set; }
public string productname { get; set; }
public string sku { get; set; }
public string productattributes { get; set; }
public string externalinput { get; set; }
public string externalinputtitle { get; set; }
public string unitlabel { get; set; }
public int quantity { get; set; }
public object decimalunitquantity { get; set; }
public string moneynetpriceperunit { get; set; }
public string moneypriceorg { get; set; }
public int vatvalue { get; set; }
public string deliveryinfo { get; set; }
public string moneyitemtotal_net { get; set; }
public string moneyitemtotal_vat { get; set; }
public int voucherid { get; set; }
public string vouchercode { get; set; }
public string vouchername { get; set; }
public string moneyoriginalprice { get; set; }
public string moneydiscountedprice { get; set; }
public string moneydiscount { get; set; }
public List<object> salestaxes { get; set; }
public string decimalquantitytotal { get; set; }
public string moneynetpriceperquantity { get; set; }
}
public class Item
{
public int orderid { get; set; }
public string moneyfinal_net { get; set; }
public string checkouttypename { get; set; }
public int orderdate { get; set; }
public int orderstateid { get; set; }
public string registerid { get; set; }
public int warehouseid { get; set; }
public string currencycode { get; set; }
public List<Orderitem> orderitems { get; set; }
public class RootObject
{
public int totalcount { get; set; }
public List<Item> items { get; set; }
}
Firstly, after fixing your JSON string which is incorrectly defined in the question and then using this Model structure in your case:
Note: For parsing Property names with special characters (like -) in your JSON, you can use the JSONProperty attribute as shown below to parse out those properties.
public class Additionaldata
{
[JsonProperty(PropertyName = "pos-timezone")]
public string postimezone { get; set; }
[JsonProperty(PropertyName = "pos-staff-externalid")]
public string posstaffexternalid { get; set; }
}
public class Orderitem
{
public int orderitemid { get; set; }
public int orderitemtype { get; set; }
public int productid { get; set; }
public string productname { get; set; }
public string sku { get; set; }
public string productattributes { get; set; }
public string externalinput { get; set; }
public string externalinputtitle { get; set; }
public string unitlabel { get; set; }
public int quantity { get; set; }
public object decimalunitquantity { get; set; }
public string moneynetpriceperunit { get; set; }
public string moneypriceorg { get; set; }
public int vatvalue { get; set; }
public string deliveryinfo { get; set; }
public string moneyitemtotal_net { get; set; }
public string moneyitemtotal_vat { get; set; }
public int voucherid { get; set; }
public string vouchercode { get; set; }
public string vouchername { get; set; }
public string moneyoriginalprice { get; set; }
public string moneydiscountedprice { get; set; }
public string moneydiscount { get; set; }
public List<object> salestaxes { get; set; }
public Additionaldata additionaldata { get; set; }
public string decimalquantitytotal { get; set; }
public string moneynetpriceperquantity { get; set; }
}
public class Item
{
public int orderid { get; set; }
public string email { get; set; }
public string namefirst { get; set; }
public string namelast { get; set; }
public string company { get; set; }
public string moneyfinal_net { get; set; }
public string moneyfinal_vat { get; set; }
public string moneytotal_gross_roundoff { get; set; }
public string moneytotal_gross_all { get; set; }
public string checkouttypename { get; set; }
public string deliverytypename { get; set; }
public int orderdate { get; set; }
public int orderstateid { get; set; }
public int paymentstateid { get; set; }
public int ordertypeid { get; set; }
public string registerid { get; set; }
public int warehouseid { get; set; }
public object datereserved { get; set; }
public string currencycode { get; set; }
public Additionaldata additionaldata { get; set; }
public List<Orderitem> orderitems { get; set; }
}
public class RootObject
{
public int totalcount { get; set; }
public List<Item> items { get; set; }
}
And finally deserializing it:
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string json=#"{'totalcount':103952,'items':[{'orderid':113951,'email':'','namefirst':'','namelast':'','company':'','moneyfinal_net':'95.92','moneyfinal_vat':'23.98','moneytotal_gross_roundoff':'0.00','moneytotal_gross_all':'119.90','checkouttypename':'Card','deliverytypename':'','orderdate':1554836745,'orderstateid':10,'paymentstateid':20,'ordertypeid':10,'registerid':'{AD16AEE2-235F-318A-4323-6B63EC2C40E7}','warehouseid':18,'datereserved':null,'currencycode':'NOK','additionaldata':{'pos-timezone':'Europe/Oslo','pos-staff-externalid':'4654'},'orderitems':[{'orderitemid':0,'orderitemtype':10,'productid':5486,'productname':'Test','sku':'320991800016','productattributes':'','externalinput':'','externalinputtitle':'','unitlabel':'ST','quantity':1,'decimalunitquantity':null,'moneynetpriceperunit':'63.92','moneypriceorg':'0.00','vatvalue':25,'deliveryinfo':'','moneyitemtotal_net':'63.92','moneyitemtotal_vat':'15.98','voucherid':0,'vouchercode':'','vouchername':'','moneyoriginalprice':'63.92','moneydiscountedprice':'0.00','moneydiscount':'0.00','salestaxes':[],'additionaldata':{},'decimalquantitytotal':'1.000','moneynetpriceperquantity':'63.92'}]}]}";
var Sresponse = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(Sresponse.totalcount);
foreach(var result in Sresponse.items)
{
Console.WriteLine(result.moneyfinal_net);
Console.WriteLine(result.additionaldata.postimezone);
foreach(var result1 in result.orderitems)
{
Console.WriteLine(result1.orderitemid);
Console.WriteLine(result1.orderitemtype);
Console.WriteLine(result1.productid);
Console.WriteLine(result1.productname);
Console.WriteLine(result1.sku);
}
}
}
}
Outputs:
103952
95.92
Europe/Oslo
0
10
5486
Test
320991800016
Working Example: https://dotnetfiddle.net/kGXBQ0
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.