This is my Json
{
"count":2,
"threads":[
{
"thread_id":346568,
"node_id":75,
"title":"Gi\u1ea3i ph\u00e1p th\u1ed5i bay m\u00f9i h\u00f4i n\u00e1ch t\u1ef1 tin h\u01a1n trong ng\u00e0y h\u00e8",
"reply_count":0,
"view_count":2,
"user_id":339597,
"username":"giangdaigia20",
"post_date":1434435728,
"sticky":0,
"discussion_state":"visible",
"discussion_open":1,
"discussion_type":"",
"first_post_id":2468576,
"first_post_likes":0,
"last_post_date":1434435728,
"last_post_id":2468576,
"last_post_user_id":339597,
"last_post_username":"giangdaigia20",
"prefix_id":2,
"block_adsense":0,
"thumbnail_url":"",
"thumbnail_cache_waindigo":"a:8:{s:13:\"thumbnail_url\";s:69:\"http:\/\/trihoinach.org\/wp-content\/uploads\/2015\/04\/Tri-hoi-nach5555.jpg\";s:12:\"thumbnailUrl\";s:69:\"http:\/\/trihoinach.org\/wp-content\/uploads\/2015\/04\/Tri-hoi-nach5555.jpg\";s:5:\"width\";s:2:\"48\";s:6:\"height\";s:2:\"48\";s:9:\"max-width\";s:2:\"48\";s:10:\"max-height\";s:2:\"48\";s:17:\"vertical-position\";i:0;s:19:\"horizontal-position\";i:0;}",
"custom_fields":[
],
"socia l_forum_id":0,
"live_waindigo":0,
"current_event_id_waindigo":0,
"google_event_id_waindigo":"",
"social_forum_title":null,
"social_forum_user_id":null,
"social_forum_style_id":null,
"absolute_url":"http:\/\/dev.handheld.vn\/threads\/346568\/"
},
{
"thread_id":346567,
"node_id":85,
"title":"Nh\u1edd c\u00e1c b\u00e1c t\u01b0 v\u1ea5n d\u00f9m em 2 c\u00e1i \u0111\u1ed3ng h\u1ed3 Citizen n\u00e0y",
"reply_count":1,
"view_count":4,
"user_id":156695,
"username":"gamap",
"post_date":1434430984,
"sticky":0,
"discussion_state":"visible",
"discussion_open":1,
"discussion_type":"",
"first_post_id":2468575,
"first_post_likes":0,
"last_post_date":1434443484,
"last_post_id":2468577,
"last_post_user_id":156695,
"last_post_username":"gamap",
"prefix_id":95,
"block_adsense":0,
"thumbnail_url":"",
"thumbnail_cache_waindigo":"a:8:{s:13:\"thumbnail_url\";s:86:\"http:\/\/i16.photobucket.com\/albums\/b3\/vozmember\/shopdongho\/citizen\/real\/BU0011-55Aa.jpg\";s:12:\"thumbnailUrl\";s:86:\"http:\/\/i16.photobucket.com\/albums\/b3\/vozmember\/shopdongho\/ci tizen\/real\/BU0011-55Aa.jpg\";s:5:\"width\";s:2:\"48\";s:6:\"height\";s:2:\"48\";s:9:\"max-width\";s:2:\"48\";s:10:\"max-height\";s:2:\"48\";s:17:\"vertical-position\";i:0;s:19:\"horizontal-position\";i:0;}",
"custom_fields":[
],
"social_forum_id":0,
"live_waindigo":0,
"current_event_id_waindigo":0,
"google_event_id_waindigo":"",
"social_forum_title":null,
"social_forum_user_id":null,
"social_forum_style_id":null,
"absolute_url":"http:\/\/dev.handheld.vn\/threads\/34656 7\/"
}
]
}
This is my class define
class Thread_Result
{
public string count { get; set; }
[JsonProperty("threads")]
public Threads threads { get; set; }
}
class Threads
{
[JsonProperty("thread_id")]
public string thread_id { get; set; }
[JsonProperty("node_id")]
public string node_id { get; set; }
[JsonProperty("title")]
public string title { get; set; }
[JsonProperty("reply_count")]
public string reply_count { get; set; }
[JsonProperty("view_count")]
public string view_count { get; set; }
[JsonProperty("user_id")]
public string user_id { get; set; }
[JsonProperty("post_date")]
public string post_date { get; set; }
[JsonProperty("sticky")]
public string sticky { get; set; }
[JsonProperty("discussion_state")]
public string discussion_state { get; set; }
[JsonProperty("discussion_open")]
public string discussion_open { get; set; }
[JsonProperty("discussion_type")]
public string discussion_type { get; set; }
[JsonProperty("first_post_id")]
public string first_post_id { get; set; }
[JsonProperty("first_post_likes")]
public string first_post_likes { get; set; }
[JsonProperty("last_post_date")]
public string last_post_date { get; set; }
[JsonProperty("last_post_id")]
public string last_post_id { get; set; }
[JsonProperty("last_post_user_id")]
public string last_post_user_id { get; set; }
[JsonProperty("last_post_username")]
public string last_post_username { get; set; }
[JsonProperty("prefix_id")]
public string prefix_id { get; set; }
[JsonProperty("block_adsense")]
public string block_adsense { get; set; }
[JsonProperty("thumbnail_url")]
public string thumbnail_url { get; set; }
[JsonProperty("thumbnail_cache_waindigo")]
public string thumbnail_cache_waindigo { get; set; }
[JsonProperty("custom_fields")]
public string custom_fields { get; set; }
[JsonProperty("social_forum_id")]
public string social_forum_id { get; set; }
[JsonProperty("live_waindigo")]
public string live_waindigo { get; set; }
[JsonProperty("current_event_id_waindigo")]
public string current_event_id_waindigo { get; set; }
[JsonProperty("google_event_id_waindigo")]
public string google_event_id_waindigo { get; set; }
[JsonProperty("social_forum_title")]
public string social_forum_title { get; set; }
[JsonProperty("social_forum_user_id")]
public string social_forum_user_id { get; set; }
[JsonProperty("social_forum_style_id")]
public string social_forum_style_id { get; set; }
[JsonProperty("absolute_url")]
public string absolute_url { get; set; }
}
But i got error
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[AppHandHeld.Class.Threads]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'count', line 1, position 9.
This is a problem for a start:
[JsonProperty("threads")]
public Threads threads { get; set; }
Which to the parser looks like:
{
"threads": { <single thread object> }
}
It needs to be:
[JsonProperty("threads")]
public Threads[] threads { get; set; }
Which looks like:
{
"threads": [<array of thread objects>]
}
Which is how it is in the JSON sample you provided. Then you also have:
[JsonProperty("custom_fields")]
public string custom_fields { get; set; }
Which would mean in the JSON:
{
"custom_fields": "<some string>"
}
However in the JSON it is in fact:
{
"custom_fields": [<an array>]
}
Which should be something like:
[JsonProperty("custom_fields")]
public string[] custom_fields { get; set; }
And again you have in Thread_Result:
[JsonProperty("count")]
public string Count { get; set; }
This should be:
[JsonProperty("count")]
public int Count { get; set; }
In fact you've done that for pretty much all of your numeric values, try and use the correct value types and let the JSON parser do the parsing for you.
Start fixing these basic issues and see how you get on.
Related
I am new to JSON string handling in C# and have the following error when trying to deserialize a JSON string:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Formula1Info.Models.clsMRData]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'MRData.xmlns', line 1, position 19.
The JSON string is:
{"MRData":{"xmlns":"http:\/\/ergast.com\/mrd\/1.5","series":"f1","url":"http://ergast.com/api/f1/1952.json","limit":"30","offset":"0","total":"8","RaceTable":{"season":"1952","Races":[{"season":"1952","round":"1","url":"http:\/\/en.wikipedia.org\/wiki\/1952_Swiss_Grand_Prix","raceName":"Swiss Grand Prix","Circuit":{"circuitId":"bremgarten","url":"http:\/\/en.wikipedia.org\/wiki\/Circuit_Bremgarten","circuitName":"Circuit Bremgarten","Location":{"lat":"46.9589","long":"7.40194","locality":"Bern","country":"Switzerland"}},"date":"1952-05-18"},{"season":"1952","round":"2","url":"http:\/\/en.wikipedia.org\/wiki\/1952_Indianapolis_500","raceName":"Indianapolis 500","Circuit":{"circuitId":"indianapolis","url":"http:\/\/en.wikipedia.org\/wiki\/Indianapolis_Motor_Speedway","circuitName":"Indianapolis Motor Speedway","Location":{"lat":"39.795","long":"-86.2347","locality":"Indianapolis","country":"USA"}},"date":"1952-05-30"},{"season":"1952","round":"3","url":"http:\/\/en.wikipedia.org\/wiki\/1952_Belgian_Grand_Prix","raceName":"Belgian Grand Prix","Circuit":{"circuitId":"spa","url":"http:\/\/en.wikipedia.org\/wiki\/Circuit_de_Spa-Francorchamps","circuitName":"Circuit de Spa-Francorchamps","Location":{"lat":"50.4372","long":"5.97139","locality":"Spa","country":"Belgium"}},"date":"1952-06-22"},{"season":"1952","round":"4","url":"http:\/\/en.wikipedia.org\/wiki\/1952_French_Grand_Prix","raceName":"French Grand Prix","Circuit":{"circuitId":"essarts","url":"http:\/\/en.wikipedia.org\/wiki\/Rouen-Les-Essarts","circuitName":"Rouen-Les-Essarts","Location":{"lat":"49.3306","long":"1.00458","locality":"Rouen","country":"France"}},"date":"1952-07-06"},{"season":"1952","round":"5","url":"http:\/\/en.wikipedia.org\/wiki\/1952_British_Grand_Prix","raceName":"British Grand Prix","Circuit":{"circuitId":"silverstone","url":"http:\/\/en.wikipedia.org\/wiki\/Silverstone_Circuit","circuitName":"Silverstone Circuit","Location":{"lat":"52.0786","long":"-1.01694","locality":"Silverstone","country":"UK"}},"date":"1952-07-19"},{"season":"1952","round":"6","url":"http:\/\/en.wikipedia.org\/wiki\/1952_German_Grand_Prix","raceName":"German Grand Prix","Circuit":{"circuitId":"nurburgring","url":"http:\/\/en.wikipedia.org\/wiki\/N%C3%BCrburgring","circuitName":"Nürburgring","Location":{"lat":"50.3356","long":"6.9475","locality":"Nürburg","country":"Germany"}},"date":"1952-08-03"},{"season":"1952","round":"7","url":"http:\/\/en.wikipedia.org\/wiki\/1952_Dutch_Grand_Prix","raceName":"Dutch Grand Prix","Circuit":{"circuitId":"zandvoort","url":"http:\/\/en.wikipedia.org\/wiki\/Circuit_Zandvoort","circuitName":"Circuit Park Zandvoort","Location":{"lat":"52.3888","long":"4.54092","locality":"Zandvoort","country":"Netherlands"}},"date":"1952-08-17"},{"season":"1952","round":"8","url":"http:\/\/en.wikipedia.org\/wiki\/1952_Italian_Grand_Prix","raceName":"Italian Grand Prix","Circuit":{"circuitId":"monza","url":"http:\/\/en.wikipedia.org\/wiki\/Autodromo_Nazionale_Monza","circuitName":"Autodromo Nazionale di Monza","Location":{"lat":"45.6156","long":"9.28111","locality":"Monza","country":"Italy"}},"date":"1952-09-07"}]}}}
and I deserialize this via this code:
var jF1Season = JsonConvert.DeserializeObject<Root>(strJSON);
The class structure is:
public class Root
{
public List<clsMRData> MRData { get; set; }
}
public class clsMRData
{
public string xmlns { get; set; }
public string series { get; set; }
public string url { get; set; }
public string limit { get; set; }
public string offset { get; set; }
public string total { get; set; }
public List<clsRaceTable> RaceTable { get; set; }
}
public class clsRaceTable
{
public string season { get; set; }
public List<clsRace> Races { get; set; }
}
public class clsRace
{
public string season { get; set; }
public string round { get; set; }
public string url { get; set; }
public string raceName { get; set; }
public List<clsCircuit> Circuit { get; set; }
public string date { get; set; }
public string time { get; set; }
}
public class clsCircuit
{
public string circuitId { get; set; }
public string url { get; set; }
public string circuitName { get; set; }
public List<clsLocation> Location { get; set; }
}
public class clsLocation
{
public string lat { get; set; }
[JsonProperty(PropertyName = "Root.MRData.RaceTable.Races.Circuit.Location.long")]
public string lon { get; set; }
public string locality { get; set; }
public string country { get; set; }
}
I guess the error is relating to how I have set this structure up, but cannot see why, so any help in solving this error would be appreciated.
you have several bugs in your code.Replace List<clsRaceTable> , List<clsCircuit> , List<clsLocation> with clsRaceTable,clsCircuit and clsLocation. Your classes should be
public class Root
{
public clsMRData MRData { get; set; }
}
public class clsMRData
{
public string xmlns { get; set; }
public string series { get; set; }
public string url { get; set; }
public string limit { get; set; }
public string offset { get; set; }
public string total { get; set; }
public clsRaceTable RaceTable { get; set; }
}
public class clsRaceTable
{
public string season { get; set; }
public List<clsRace> Races { get; set; }
}
public class clsRace
{
public string season { get; set; }
public string round { get; set; }
public string url { get; set; }
public string raceName { get; set; }
public clsCircuit Circuit { get; set; }
public string date { get; set; }
public string time { get; set; }
}
public class clsCircuit
{
public string circuitId { get; set; }
public string url { get; set; }
public string circuitName { get; set; }
public clsLocation Location { get; set; }
}
public class clsLocation
{
public string lat { get; set; }
[JsonProperty(PropertyName = "long")]
public string lon { get; set; }
public string locality { get; set; }
public string country { get; set; }
}
I have below Json -
{"property_id":"53863730","name":"Hayat Elhamra","address":{"line_1":"Jeddah","city":"Jeddah","state_province_name":"Jeddah","postal_code":"23212","country_code":"SA","obfuscation_required":false,"localized":{"links":{"ar-SA":{"method":"GET","href":"https://api.ean.com/2.4/properties/content?language=ar-SA&property_id=53863730&include=address"}}}},"location":{"coordinates":{"latitude":21.520902,"longitude":39.158265}},"phone":"20-01145772035","category":{"id":"16","name":"Apartment"},"rank":99999999,"business_model":{"expedia_collect":true,"property_collect":true},"dates":{"added":"2020-06-10T23:03:21.345Z","updated":"2020-06-10T23:03:23.701Z"},"chain":{"id":"0","name":"Independent"},"brand":{"id":"0","name":"Independent"}}
{"property_id":"53183065","name":"Carefully Furnished Bungalow With 2 Bathrooms, 7km From Pula","address":{"line_1":"1 x M 90,3","line_2":"PRIVATE_VACATION_HOME 3","city":"Fazana","state_province_name":"Istria (county)","postal_code":"52212","country_code":"HR","obfuscation_required":true,"localized":{"links":{"hr-HR":{"method":"GET","href":"https://api.ean.com/2.4/properties/content?language=hr-HR&property_id=53183065&include=address"}}}},"ratings":{"property":{"rating":"3.0","type":"Star"}},"location":{"coordinates":{"latitude":44.93,"longitude":13.8}},"phone":"410442743080","category":{"id":"17","name":"Private vacation home"},"rank":99999999,"business_model":{"expedia_collect":true,"property_collect":false},"dates":{"added":"2020-05-13T21:06:42.861Z","updated":"2020-05-18T21:57:39.242Z"},"statistics":{"1073743378":{"id":"1073743378","name":"Number of bedrooms - 2","value":"2"},"1073743380":{"id":"1073743380","name":"Max occupancy - 4","value":"4"},"1073743379":{"id":"1073743379","name":"Number of bathrooms - 2","value":"2"}},"chain":{"id":"7278","name":"Belvilla"},"brand":{"id":"7353","name":"Belvilla"}}
{"property_id":"53182898","name":"Snug Cottage in Pašman With Roofed Terrace","address":{"line_1":"Pasman","city":"Pasman","state_province_name":"Zadar","postal_code":"23260","country_code":"HR","obfuscation_required":true,"localized":{"links":{"hr-HR":{"method":"GET","href":"https://api.ean.com/2.4/properties/content?language=hr-HR&property_id=53182898&include=address"}}}},"ratings":{"property":{"rating":"1.0","type":"Star"}},"location":{"coordinates":{"latitude":43.891571,"longitude":15.423619}},"phone":"410442743080","category":{"id":"11","name":"Cottage"},"rank":99999999,"business_model":{"expedia_collect":true,"property_collect":false},"dates":{"added":"2020-05-13T21:13:49.155Z","updated":"2020-05-27T21:02:31.808Z"},"statistics":{"1073743378":{"id":"1073743378","name":"Number of bedrooms - 2","value":"2"},"1073743380":{"id":"1073743380","name":"Max occupancy - 5","value":"5"},"1073743379":{"id":"1073743379","name":"Number of bathrooms - 1","value":"1"}},"chain":{"id":"7278","name":"Belvilla"},"brand":{"id":"7353","name":"Belvilla"}}
For this I have created below class structure -
public class Property
{
public string property_id { get; set; }
public string name { get; set; }
public Address address { get; set; }
public Location location { get; set; }
public string phone { get; set; }
public Category category { get; set; }
public int rank { get; set; }
public Business_Model business_model { get; set; }
public Dates dates { get; set; }
public Chain chain { get; set; }
public Brand brand { get; set; }
}
public class Address
{
public string line_1 { get; set; }
public string city { get; set; }
public string state_province_name { get; set; }
public string postal_code { get; set; }
public string country_code { get; set; }
public bool obfuscation_required { get; set; }
public Localized localized { get; set; }
}
public class Localized
{
public Links links { get; set; }
}
public class Links
{
public ArSA arSA { get; set; }
}
public class ArSA
{
public string method { get; set; }
public string href { get; set; }
}
public class Location
{
public Coordinates coordinates { get; set; }
}
public class Coordinates
{
public float latitude { get; set; }
public float longitude { get; set; }
}
public class Category
{
public string id { get; set; }
public string name { get; set; }
}
public class Business_Model
{
public bool expedia_collect { get; set; }
public bool property_collect { get; set; }
}
public class Dates
{
public DateTime added { get; set; }
public DateTime updated { get; set; }
}
public class Chain
{
public string id { get; set; }
public string name { get; set; }
}
public class Brand
{
public string id { get; set; }
public string name { get; set; }
}
I have below code where I am getting error -
using (StreamReader streamReader = new StreamReader("d://propertycontent.expediacollect.en-US.json"))
{
using (var json = new JsonTextReader(streamReader))
{
JsonSerializer serializer = new JsonSerializer();
var properties= (List<Property>)serializer.Deserialize(json, typeof(List<Property>));
}
}
Error -
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Property]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'property_id', line 1, position 15.'
It is not deserializing because it is not valid json. To make it valid, and to make it a List<Property> add [ to the beginning of the json and ] to the end of the json. Just enclose the json in [ ... ] to make it valid and it will deserialize assuming the rest of it is valid and is not missing any commas or brackets.
try this, you will have to install NewtonsoftJson. It was tested using Visual Studio and Postman and works properly.
var jsonOrig= ...your json
var json = JsonConvert.SerializeObject(jsonOrig);
var jsonObj = JsonConvert.DeserializeObject<DataRoot>(json);
classes
public class DataRoot
{
public string property_id { get; set; }
public string name { get; set; }
public Address address { get; set; }
public Location location { get; set; }
public string phone { get; set; }
public Category category { get; set; }
public int rank { get; set; }
public BusinessModel business_model { get; set; }
public Dates dates { get; set; }
public Chain chain { get; set; }
public Brand brand { get; set; }
}
public class ArSA
{
public string method { get; set; }
public string href { get; set; }
}
public class Links
{
[JsonProperty("ar-SA")]
public ArSA ArSA { get; set; }
}
public class Localized
{
public Links links { get; set; }
}
public class Address
{
public string line_1 { get; set; }
public string city { get; set; }
public string state_province_name { get; set; }
public string postal_code { get; set; }
public string country_code { get; set; }
public bool obfuscation_required { get; set; }
public Localized localized { get; set; }
}
public class Coordinates
{
public double latitude { get; set; }
public double longitude { get; set; }
}
public class Location
{
public Coordinates coordinates { get; set; }
}
public class Category
{
public string id { get; set; }
public string name { get; set; }
}
public class BusinessModel
{
public bool expedia_collect { get; set; }
public bool property_collect { get; set; }
}
public class Dates
{
public DateTime added { get; set; }
public DateTime updated { get; set; }
}
public class Chain
{
public string id { get; set; }
public string name { get; set; }
}
public class Brand
{
public string id { get; set; }
public string name { get; set; }
}
`````
I need to deserialize a JSON respons from the FastBill API, (I'm using JSON .NET) I've created the C# class who will "hold" the data retrieved from the API response, the problem is that the response from the server is bad, looks like this:
"{
\"REQUEST\":{
\"SERVICE\":\"invoice.get\",
\"LIMIT\":1,
\"FILTER\":{
\"YEAR\":2018
}
},
\"RESPONSE\":{
\"INVOICES\":[{
\"INVOICE_ID\":\"11586818\",
\"TYPE\":\"outgoing\",
\"CUSTOMER_ID\":\"4735248\",
\"CUSTOMER_NUMBER\":\"3211\",
\"CUSTOMER_COSTCENTER_ID\":\"0\",
\"CONTACT_ID\":\"\",
\"PROJECT_ID\":\"0\",
\"CURRENCY_CODE\":\"EUR\",
\"DELIVERY_DATE\":\"02.01.2018\",
\"INVOICE_TITLE\":\"Rechnung f\\u00fcr Ihre Bestellung bei Amazon\",
\"CASH_DISCOUNT_PERCENT\":\"0.00\",
\"CASH_DISCOUNT_DAYS\":\"0\",
\"SUB_TOTAL\":22.66,
\"VAT_TOTAL\":4.31,
\"VAT_ITEMS\":[{
\"VAT_PERCENT\":\"19.00\",
\"COMPLETE_NET\":22.66,
\"VAT_VALUE\":4.3061344545
}],
\"ITEMS\":[{
\"INVOICE_ITEM_ID\":\"33975736\",
\"ARTICLE_NUMBER\":\"CK-7I70-IBD4\",
\"DESCRIPTION\":\"Gr\\u00fcne Elefanten\\\\'s Bio OPC Traubenkernextrakt mit Bio Acerola Hochdosiert 2 Monatsvorrat - 390mg Kapseln Trauben aus Frankreich\",
\"QUANTITY\":\"1.0000\",
\"UNIT_PRICE\":\"22.66386555\",
\"VAT_PERCENT\":\"19.00\",
\"VAT_VALUE\":4.3061344545,
\"COMPLETE_NET\":22.66386555,
\"COMPLETE_GROSS\":26.9700000045,
\"SORT_ORDER\":1
}],
\"TOTAL\":26.97,
\"ORGANIZATION\":\"\",
\"NOTE\":\"\",
\"SALUTATION\":\"\",
\"FIRST_NAME\":\"NAME\",
\"LAST_NAME\":\"NAME\",
\"ADDRESS\":\"ADDRESS\",
\"ADDRESS_2\":\" \",
\"ZIPCODE\":\"97493\",
\"CITY\":\"CITY\",
\"PAYMENT_TYPE\":\"1\",
\"BANK_NAME\":\"\",
\"BANK_ACCOUNT_NUMBER\":\"\",
\"BANK_CODE\":\"\",
\"BANK_ACCOUNT_OWNER\":\"\",
\"BANK_IBAN\":\"\",
\"BANK_BIC\":\"\",
\"COUNTRY_CODE\":\"DE\",
\"VAT_ID\":\"\",
\"TEMPLATE_ID\":\"963360\",
\"INVOICE_NUMBER\":\"3209\",
\"INTROTEXT\":\"wir bedanken uns f\\u00fcr Ihre Bestellung bei Amazon (Bestellnummer 306-9638137-3397961). Der Zahlungsbetrag wurde bereits entrichtet.\",
\"PAID_DATE\":\"2018-01-02 00:00:00\",
\"IS_CANCELED\":\"0\",
\"INVOICE_DATE\":\"2018-01-02\",
\"DUE_DATE\":\"0000-00-00 00:00:00\",
\"PAYMENT_INFO\":\"01\\\/02\\\/2018 26,
97 \\u20ac () \",
\"PAYMENTS\":[{
\"PAYMENT_ID\":\"7640244\",
\"DATE\":\"01\\\/02\\\/2018\",
\"AMOUNT\":\"26.97\",
\"CURRENCY_CODE\":\"EUR\",
\"NOTE\":\"\",
\"TYPE\":\"\"
}],
\"LASTUPDATE\":\"2018-01-02 17:29:21\",
\"DOCUMENT_URL\":\"https:\\\/\\\/my.fastbill.com\\\/download\\\/DD0fDZvD1CUfB2S4TvLy8GgCuGNKqfbuiNLmn6pa895-yK0E6.20FV3zbC9EhWyC\"
}]
}
}"
(The backslashes seems to appear only in the debugger, so isn't this the problem.)
If I left the response exactly as this, the runtime doesn't give any error, but the JsonConvert.DeserializeObject doesn't return the data from the response in the "fields" of the C# class, otherwise, if I remove the REQUEST and the RESPONSE header and leave only the INVOICES items, seems to "work", but now a new error appears from the compiler:
'Unexpected character encountered while parsing value: {. Path 'VAT_ITEMS', line 1, position 373.'
The C# class:
public class GET_INVOICE {
public string INVOICE_ID { get; set; }
public string TYPE { get; set; }
public string CUSTOMER_ID { get; set; }
public string CUSTOMER_NUMBER { get; set; }
public string CUSTOMER_COSTCENTER_ID { get; set; }
public string CONTACT_ID { get; set; }
public string PROJECT_ID { get; set; }
public string CURRENCY_CODE { get; set; }
public string DELIVERY_DATE { get; set; }
public string INVOICE_TITLE { get; set; }
public string CASH_DISCOUNT_PERCENT { get; set; }
public string CASH_DISCOUNT_DAYS { get; set; }
public string SUB_TOTAL { get; set; }
public string VAT_TOTAL { get; set; }
public IList<string> VAT_ITEMS { get; set; }
public IList<string> ITEMS { get; set; }
public double TOTAL { get; set; }
public string ORGANIZATION { get; set; }
public string NOTE { get; set; }
public string SALUTATION { get; set; }
public string FIRST_NAME { get; set; }
public string LAST_NAME { get; set; }
public string ADDRESS { get; set; }
public string ADDRESS_2 { get; set; }
public string ZIPCODE { get; set; }
public string CITY { get; set; }
public string PAYMENT_TYPE { get; set; }
public string BANK_NAME { get; set; }
public string BANK_ACCOUNT_NUMBER { get; set; }
public string BANK_CODE { get; set; }
public string BANK_ACCOUNT_OWNER { get; set; }
public string BANK_IBAN { get; set; }
public string BANK_BIC { get; set; }
public string COUNTRY_CODE { get; set; }
public string VAT_ID { get; set; }
public string TEMPLATE_ID { get; set; }
public string INVOICE_NUMBER { get; set; }
public string INTROTEXT { get; set; }
public string PAID_DATE { get; set; }
public string IS_CANCELED { get; set; }
public string INVOICE_DATE { get; set; }
public string DUE_DATE { get; set; }
public string PAYMENT_INFO { get; set; }
public IList<string> PAYMENTS { get; set; }
public string LASTUPDATE { get; set; }
public string DOCUMENT_URL { get; set; }
}
The deserialization
JSON.GET_INVOICE GetInvoiceStruct = JsonConvert.DeserializeObject<JSON.GET_INVOICE>(_response);
I really don't understand how I can successfully deserialize the response.
You've successfully prepared model for main object you are deserializing.
Now you also need to model additional models for your collections:
VAT_ITEMS
ITEMS
PAYMENTS
Currently you've modeled them as string but they are not strings at all, they are complex objects.
I'll provide you with example for VatItem and then you can complete the rest yourself.
Create VatItem model, ie:
public class VatItem
{
//Did not used decimal type because I don't know how JSON.NET handles it
public double VAT_PERCENT { get; set; }
public double COMPLETE_NET { get; set; }
public double VAT_VALUE { get; set; }
}
to model this part of json response:
\"VAT_PERCENT\":\"19.00\",
\"COMPLETE_NET\":22.66,
\"VAT_VALUE\":4.3061344545
Then change in GET_INVOICE model your VAT_ITEMS collection to be:
public IList<VatItem> VAT_ITEMS { get; set; }
Follow the example with two additional collections to complete mapping.
I am using Newtonsoft.JSON in C# and I have JSON like this:
http://woothemes.github.io/woocommerce/rest-api/#get-orders
Note:
coupon_lines []
When I serialize the JSON, I get this error:
List<Order> result = JObject.Parse(GetJson(url))["orders"].ToObject<List<Order>>();
Here is the coupon json:
"coupon_lines":{"id":65,"code":"alank10","amount":"33.08"}
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WooCommerce.Core.Models.CouponLine]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
How do I serialize coupon_lines to List
public class CouponLine
{
public int id { get; set; }
public string code { get; set; }
public decimal amount { get; set; }
}
Here is my class:
public class CouponLines
{
public List<CouponLine> lines { get; set; }
}
public class Order
{
public int id { get; set; }
public string order_number { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
public DateTime completed_at { get; set; }
public string status { get; set; }
public string currency { get; set; }
public decimal total { get; set; }
public decimal subtotal { get; set; }
public int total_line_items_quantity { get; set; }
public decimal total_tax { get; set; }
public decimal total_shipping { get; set; }
public decimal cart_tax { get; set; }
public decimal shipping_tax { get; set; }
public decimal total_discount { get; set; }
public decimal cart_discount { get; set; }
public decimal order_discount { get; set; }
public string shipping_methods { get; set; }
public PaymentDetails payment_details { get; set; }
public BillingAddress billing_address { get; set; }
public ShippingAddress shipping_address { get; set; }
public string note { get; set; }
public string customer_ip { get; set; }
public string customer_user_agent { get; set; }
public string customer_id { get; set; }
public string view_order_url { get; set; }
public List<LineItem> line_items { get; set; }
public List<ShippingLine> shipping_lines { get; set; }
//public List<object> tax_lines { get; set; }
//public List<object> fee_lines { get; set; }
public CouponLines coupon_lines { get; set; }
public Customer customer { get; set; }
}
You should use some kind of "root" object that contains this list, for example:
var parsedResponse = JsonConvert.DeserializeObject<CouponLines>(jsonResponse);
//...
public class CouponLines
{
public List<CouponLine> order { get; set; }
}
The string from your example
"coupon_lines":{"id":65,"code":"alank10","amount":"33.08"}
is invalid JSON: to make it valid add { at the beginning and } at the end:
{"coupon_lines":{"id":65,"code":"alank10","amount":"33.08"}}
Also, you said, you want to deserialize list, and you do not have list in your example. To get list your JSON object should contain list of objects (even if there is one object) in square breckets []:
{
"coupon_lines":[
{
"id":65,
"code":"alank10",
"amount":"33.08"
}
//if you have several objects - put it here after comma:
//,
//{
// "id":100500,
// "code":"somecode",
// "amount":"33.08"
//}
]
}
I had a similar problem (and also similar reuqest with orders, lines, shippings etc...)
first thing is that:
in your json, you can receive your list as
"line_items" : null
without any problems
or also this one:
"line_items" : []
does the trick.
but if you want the perfect solution, so you can avoid to send the line_items parameter completely, the solution is pretty easy,
just decorate your property on the request with
[JsonProperty(Required = Required.AllowNull)]
public List<LineItem> line_items { get; set; }
it worked perfectly for me.
I have next JSON:
[
{
"ApplicationRelations":[
{
"Application":null,
"ApplicationSubcategory":null,
"ApplicationCategory":{
"categoryName":"Default Category",
"id":4
},
"roleOrder":null,
"categoryOrder":null,
"subcategoryOrder":null,
"applicationOrder":null,
"id":6
},
{
"Application":{
"launchUrl":"link",
"trainingUrl":"link",
"installUrl":"link",
"vpn":true,
"overview":"text",
"summary":"text",
"id":12,
"title":"Application"
},
"ApplicationSubcategory":{
"subcategoryName":"Creation",
"id":9
},
"ApplicationCategory":{
"categoryName":"Default Category",
"id":4
},
"roleOrder":15,
"categoryOrder":25,
"subcategoryOrder":35,
"applicationOrder":45,
"id":15
}
],
"roleName":"Role 02",
"roleHeader":"Header of Role 02",
"AnnouncementRelations":[
],
"id":2
}
]
And here are my C# clases:
public class Applications
{
public List<SalesCentralApplicationRelation> salesCentralApplicationRelations { get; set; }
public string RoleName { get; set; }
public string RoleHeader { get; set; }
public List<object> SalesCentralAnnouncementRelations { get; set; }
public int Id { get; set; }
}
public class SalesCentralApplicationRelation
{
public SalesCentralApplication salesCentralApplication { get; set; }
public SalesCentralApplicationSubcategory salesCentralApplicationSubcategory { get; set; }
public SalesCentralApplicationCategory salesCentralApplicationCategory { get; set; }
public int roleOrder { get; set; }
public int categoryOrder { get; set; }
public int subcategoryOrder { get; set; }
public int applicationOrder { get; set; }
public int id { get; set; }
}
public class SalesCentralApplicationCategory
{
public string categoryName { get; set; }
public int id { get; set; }
}
public class SalesCentralApplicationSubcategory
{
public string subcategoryName { get; set; }
public int id { get; set; }
}
public class SalesCentralApplication
{
public string launchUrl { get; set; }
public string trainingUrl { get; set; }
public string installUrl { get; set; }
public bool vpn { get; set; }
public string overview { get; set; }
public string summary { get; set; }
public int id { get; set; }
public string title { get; set; }
}
And my deserialization:
var contents //JSON string above
Applications ApplicationsList = JsonConvert.DeserializeObject<Applications>(contents) as Applications;
And code fails with:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'App1.MainPage+Applications' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
Checked my classes with json2csharp - all is fine... where is the problem?
Your json is an array, not a single object. Try this:
var ApplicationsList = JsonConvert.DeserializeObject<List<Applications>>(contents);