json to c# deserialization with json.net - c#

I know there has been countless posts about json deserialization, but I have followed most of the posts answers, and they haven't worked out. I think my main issue is I can't seem to wrap my head around how Json actually is built up structure-wise.
I have following Json string from an API:
{
"totalCount_str": "3",
"items": [
{
"standing": 10,
"corporation": {
"name": "borkedLabs",
"isNPC": false,
"href": "https://crest-tq.eveonline.com/corporations/98046548/",
"id_str": "98046548",
"logo": {
"32x32": {
"href": "http://imageserver.eveonline.com/Corporation/98046548_32.png"
},
"64x64": {
"href": "http://imageserver.eveonline.com/Corporation/98046548_64.png"
},
"128x128": {
"href": "http://imageserver.eveonline.com/Corporation/98046548_128.png"
},
"256x256": {
"href": "http://imageserver.eveonline.com/Corporation/98046548_256.png"
}
},
"id": 98046548
},
"href": "https://crest-tq.eveonline.com/characters/94512721/contacts/98046548/",
"contact": {
"id_str": "98046548",
"href": "https://crest-tq.eveonline.com/corporations/98046548/",
"name": "borkedLabs",
"id": 98046548
},
"contactType": "Corporation"
},
{
"standing": 10,
"character": {
"name": "xxxx yyyy",
"corporation": {
"name": "xxyshs",
"isNPC": false,
"href": "https://crest-tq.eveonline.com/corporations/98401169/",
"id_str": "98401169",
"logo": {
"32x32": {
"href": "http://imageserver.eveonline.com/Corporation/98401169_32.png"
},
"64x64": {
"href": "http://imageserver.eveonline.com/Corporation/98401169_64.png"
},
"128x128": {
"href": "http://imageserver.eveonline.com/Corporation/98401169_128.png"
},
"256x256": {
"href": "http://imageserver.eveonline.com/Corporation/98401169_256.png"
}
},
"id": 98401169
},
"isNPC": false,
"href": "https://crest-tq.eveonline.com/characters/95161569/",
"capsuleer": {
"href": "https://crest-tq.eveonline.com/characters/95161569/capsuleer/"
},
"portrait": {
"32x32": {
"href": "http://imageserver.eveonline.com/Character/95161569_32.jpg"
},
"64x64": {
"href": "http://imageserver.eveonline.com/Character/95161569_64.jpg"
},
"128x128": {
"href": "http://imageserver.eveonline.com/Character/95161569_128.jpg"
},
"256x256": {
"href": "http://imageserver.eveonline.com/Character/95161569_256.jpg"
}
},
"id": 95161569,
"id_str": "95161569"
},
"contact": {
"id_str": "95161569",
"href": "https://crest-tq.eveonline.com/characters/95161569/",
"name": "xxxx yyyy",
"id": 95161569
},
"href": "https://crest-tq.eveonline.com/characters/94512769/contacts/95161569/",
"contactType": "Character",
"watched": false,
"blocked": false
},
{
"standing": -10,
"alliance": {
"id_str": "99000003",
"href": "http://crest.regner.dev/alliances/99000003/",
"id": 99000003,
"name": "One One Corporation Alliance"
},
"href": "http://crest.regner.dev/characters/90000001/contacts/99000003/",
"contact": {
"id_str": "99000003",
"href": "http://crest.regner.dev/alliances/99000003/",
"name": "One One Corporation Alliance",
"id": 99000003
},
"contactType": "Alliance"
}
],
"pageCount": 1,
"pageCount_str": "1",
"totalCount": 3
}
Note that the items array can contain any number of "contacts".
By using http://json2csharp.com/ I have converted it to classes in C# as following:
public class Contacts
{
public string totalCount_str { get; set; }
public Item[] items { get; set; }
public int pageCount { get; set; }
public string pageCount_str { get; set; }
public int totalCount { get; set; }
}
public class Item
{
public int standing { get; set; }
public Alliance alliance { get; set; }
public string href { get; set; }
public Contact contact { get; set; }
public string contactType { get; set; }
public Character character { get; set; }
public bool watched { get; set; }
public bool blocked { get; set; }
}
public class Alliance
{
public string id_str { get; set; }
public string href { get; set; }
public int id { get; set; }
public string name { get; set; }
}
public class Contact
{
public string id_str { get; set; }
public string href { get; set; }
public string name { get; set; }
public int id { get; set; }
}
public class Character
{
public string name { get; set; }
public Corporation corporation { get; set; }
public bool isNPC { get; set; }
public string href { get; set; }
public Capsuleer capsuleer { get; set; }
public Portrait portrait { get; set; }
public int id { get; set; }
public string id_str { get; set; }
}
public class Corporation
{
public string name { get; set; }
public bool isNPC { get; set; }
public string href { get; set; }
public string id_str { get; set; }
public Logo logo { get; set; }
public int id { get; set; }
}
public class Logo
{
public _32X32 _32x32 { get; set; }
public _64X64 _64x64 { get; set; }
public _128X128 _128x128 { get; set; }
public _256X256 _256x256 { get; set; }
}
public class _32X32
{
public string href { get; set; }
}
public class _64X64
{
public string href { get; set; }
}
public class _128X128
{
public string href { get; set; }
}
public class _256X256
{
public string href { get; set; }
}
public class Capsuleer
{
public string href { get; set; }
}
public class Portrait
{
public _32X32 _32x32 { get; set; }
public _64X64 _64x64 { get; set; }
public _128X128 _128x128 { get; set; }
public _256X256 _256x256 { get; set; }
}
And then trying to deserialize it with:
List<Contacts> tempList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Contacts>>(response.Content);
I appreciate any help that could get me on the right tracks. I get an error currently when trying this way:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ContactWatchlister.Models.Contacts]' 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 'totalCount_str', line 1, position 18.
I am currently stuck as I don't get why it is having trouble understanding "totalCount_str" into a string.
I have tried to use [JsonProperty("attribute")] on all attributes in my classes to model it correct, but same error.
I'm pretty sure I am doing something rather simple, wrong, but I can't wrap my head around it. Hope you can help! :-)

If response.Content contains the JSON string you described I think the statement should be:
var tempList = Newtonsoft.Json.JsonConvert.DeserializeObject<Contacts>(response.Content);
Your JSON has the "totalCount_str", items, pageCount, pageCount_str and totalCount fields in the outermost "level", so it can only be deserialized into a class that has those properties (or properties with correct JsonAttributes that correspond to those fieldnames).
The one you tried would work with the following JSON, where the outermost entity is an array:
[ {
"totalCount_str": "3",
"items": [
{
"standing": 10,
"corporation": {
"name": "borkedLabs",
"isNPC": false,
"href": "https://crest-tq.eveonline.com/corporations/98046548/",
"id_str": "98046548",
"logo": {
"32x32": {
"href": "http://imageserver.eveonline.com/Corporation/98046548_32.png"
},
"64x64": {
"href": "http://imageserver.eveonline.com/Corporation/98046548_64.png"
},
"128x128": {
"href": "http://imageserver.eveonline.com/Corporation/98046548_128.png"
},
"256x256": {
"href": "http://imageserver.eveonline.com/Corporation/98046548_256.png"
}
},
"id": 98046548
},
"href": "https://crest-tq.eveonline.com/characters/94512721/contacts/98046548/",
"contact": {
"id_str": "98046548",
"href": "https://crest-tq.eveonline.com/corporations/98046548/",
"name": "borkedLabs",
"id": 98046548
},
"contactType": "Corporation"
},
{
"standing": 10,
"character": {
"name": "xxxx yyyy",
"corporation": {
"name": "xxyshs",
"isNPC": false,
"href": "https://crest-tq.eveonline.com/corporations/98401169/",
"id_str": "98401169",
"logo": {
"32x32": {
"href": "http://imageserver.eveonline.com/Corporation/98401169_32.png"
},
"64x64": {
"href": "http://imageserver.eveonline.com/Corporation/98401169_64.png"
},
"128x128": {
"href": "http://imageserver.eveonline.com/Corporation/98401169_128.png"
},
"256x256": {
"href": "http://imageserver.eveonline.com/Corporation/98401169_256.png"
}
},
"id": 98401169
},
"isNPC": false,
"href": "https://crest-tq.eveonline.com/characters/95161569/",
"capsuleer": {
"href": "https://crest-tq.eveonline.com/characters/95161569/capsuleer/"
},
"portrait": {
"32x32": {
"href": "http://imageserver.eveonline.com/Character/95161569_32.jpg"
},
"64x64": {
"href": "http://imageserver.eveonline.com/Character/95161569_64.jpg"
},
"128x128": {
"href": "http://imageserver.eveonline.com/Character/95161569_128.jpg"
},
"256x256": {
"href": "http://imageserver.eveonline.com/Character/95161569_256.jpg"
}
},
"id": 95161569,
"id_str": "95161569"
},
"contact": {
"id_str": "95161569",
"href": "https://crest-tq.eveonline.com/characters/95161569/",
"name": "xxxx yyyy",
"id": 95161569
},
"href": "https://crest-tq.eveonline.com/characters/94512769/contacts/95161569/",
"contactType": "Character",
"watched": false,
"blocked": false
},
{
"standing": -10,
"alliance": {
"id_str": "99000003",
"href": "http://crest.regner.dev/alliances/99000003/",
"id": 99000003,
"name": "One One Corporation Alliance"
},
"href": "http://crest.regner.dev/characters/90000001/contacts/99000003/",
"contact": {
"id_str": "99000003",
"href": "http://crest.regner.dev/alliances/99000003/",
"name": "One One Corporation Alliance",
"id": 99000003
},
"contactType": "Alliance"
}
],
"pageCount": 1,
"pageCount_str": "1",
"totalCount": 3 } ]

Related

C# DeserializeObject change class attribute name

Hello I have one json text one attribute includes $type. I want to change it to type in my response but it is again written as $type.
public class DocumentDTO
{
public string Version { get; set; }
public List<DocumentInfo> Documents { get; set; }
}
public class DocumentInfo
{
public string DocumentState { get; set; }
public DocumentData DocumentData { get; set; }
public string DocumentAsBase64 { get; set; }
}
public class DocumentData
{
public string Name { get; set; }
[JsonProperty(PropertyName = "$type")]
public string type { get; set; }
public List<DocumentField> Fields { get; set; }
}
public class DocumentField
{
public string Name { get; set; }
[JsonProperty(PropertyName = "$type")]
public string type { get; set; }
public string SuspiciousSymbols { get; set; }
public string RecognizedValue { get; set; }
public string Value { get; set; }
}
I am deserializing like below code
DocumentDTO documentResult = JsonConvert.DeserializeObject<DocumentDTO>(jsonText);
In my api response it is still as $type even I want type. What is my missing here?
Below one is not my want
{
"message": null,
"hasError": false,
"errors": [],
"data": [
{
"version": "1.1",
"documents": [
{
"documentState": "Correct",
"documentData": {
"name": "OthersTWN",
"$type": "Document",
"fields": [
{
"name": "DocumentGUID",
"$type": "Text",
"suspiciousSymbols": null,
"recognizedValue": null,
"value": ""
}
]
},
"documentAsBase64": ""
}
]
}
],
"percentage": 100
}
Below one is my want
{
"message": null,
"hasError": false,
"errors": [],
"data": [
{
"version": "1.1",
"documents": [
{
"documentState": "Correct",
"documentData": {
"name": "OthersTWN",
"type": "Document",
"fields": [
{
"name": "DocumentGUID",
"type": "Text",
"suspiciousSymbols": null,
"recognizedValue": null,
"value": ""
}
]
},
"documentAsBase64": ""
}
]
}
],
"percentage": 100
}
Thanks in advance

C# Convert my JsonSchema's Properties to Json Schema and add new fields on the fly

I created my own JsonSchema with some standard properties.
public class JsonSchema
{
public SchemaType Type { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Const { get; set; }
public IList<Dictionary<string, object>> Properties { get; set; }
public IList<object> Enum { get; set; }
public IList<JsonSchema> Items { get; set; }
public IList<string> Required { get; set; }
public IList<JsonSchema> AllOf { get; set; }
public IList<JsonSchema> AnyOf { get; set; }
public IList<JsonSchema> OneOf { get; set; }
}
and I need to convert it to Json Schema string.
I'm using the JsonConvert.SerializeObject to convert it.
Almost everything is Ok, but the property 'Properties' is being converted to an array of JsonSchema as follow:
{
"type": "object",
"properties": [
{
"f_1022": {
"type": "string",
"title": "Zona",
"oneOf": [
{
"title": "Urbana",
"description": "Urbana",
"const": "o_1043"
},
{
"title": "Rural",
"description": "Rural",
"const": "o_1044"
},
{
"title": "Periurbana",
"description": "Periurbana",
"const": "o_1045"
}
]
}
},
{
"f_1023": {
"type": "string",
"title": "Etnia/Cor"
}
},
]
}
And I need the result be like this:
{
"type": "object",
"properties":
{
"f_1022": {
"type": "string",
"title": "Zona",
"oneOf": [
{
"title": "Urbana",
"description": "Urbana",
"const": "o_1043"
},
{
"title": "Rural",
"description": "Rural",
"const": "o_1044"
},
{
"title": "Periurbana",
"description": "Periurbana",
"const": "o_1045"
}
]
},
"f_1023": {
"type": "string",
"title": "Etnia/Cor"
}
}
}
Note that the last Json Properties don't have the brackets.
How can I make the JsonConvert convert like the last Json Schema?
Thanks

JSON.net deserialize object nested data

I'm working with SwiftType Elastic Search + C# and running into an issue deserializing the response due to the fact that SwiftType returns all of the fields as objects with a raw property (https://swiftype.com/documentation/app-search/api/search) for example:
{
"meta": {
"warnings": [],
"page": {
"current": 1,
"total_pages": 1,
"total_results": 2,
"size": 10
},
"request_id": "6887a53f701a59574a0f3a7012e01aa8"
},
"results": [
{
"phone": {
"raw": 3148304280.0
},
"accounts_balance_ach": {
"raw": 27068128.71
},
"accounts_balance_pending": {
"raw": "46809195.64"
},
"email": {
"raw": "Brisa34#hotmail.com"
},
"accounts_count": {
"raw": 6.0
},
"id": {
"raw": "c98808a2-d7d6-4444-834d-2fe4f6858f6b"
},
"display_name": {
"raw": "The Johnstons"
},
"type": {
"raw": "Couple"
},
"advisor_email": {
"raw": "Cornelius_Schiller14#hotmail.com"
},
"created_at": {
"raw": "2018-10-02T10:42:07+00:00"
},
"source": {
"raw": "event"
},
"accounts_balance": {
"raw": 43629003.47
},
"accounts_donations": {
"raw": 38012278.75
},
"advisor_name": {
"raw": "Cloyd Jakubowski"
},
"_meta": {
"score": 0.42934617
}
},
{
"phone": {
"raw": 2272918612.0
},
"accounts_balance_ach": {
"raw": 35721452.35
},
"accounts_balance_pending": {
"raw": "35117465.2"
},
"email": {
"raw": "Ruby87#yahoo.com"
},
"accounts_count": {
"raw": 1.0
},
"id": {
"raw": "687af11f-0f73-4112-879c-1108303cb07a"
},
"display_name": {
"raw": "Kennith Johnston"
},
"type": {
"raw": "Individual"
},
"advisor_email": {
"raw": "Evangeline_Wisoky92#hotmail.com"
},
"created_at": {
"raw": "2018-10-02T16:16:02+00:00"
},
"source": {
"raw": "website"
},
"accounts_balance": {
"raw": 23063874.19
},
"accounts_donations": {
"raw": 33025175.79
},
"advisor_name": {
"raw": "Ernie Mertz"
},
"_meta": {
"score": 0.39096162
}
}
]
}
I need to map each key to its value, eg results[0].email = "Brisa34#hotmail.com";
I saw a promising option with custom converters but I want to make sure there is not a more dynamic way to do this before I take the verbose approach.
I would suggest using the JsonPathConverter class found in Can I specify a path in an attribute to map a property in my class to a child property in my JSON?. This will allow you to declare a strongly-typed Result class and then easily map each of the properties to the value of the respective raw child value in the JSON without having to declare a ton of awkward single-property classes.
Declare your model as shown below. Note that the Result class needs a [JsonConverter] attribute on it to tie it to the JsonPathConverter (otherwise the property paths will not work and you will get default values in your properties).
public class RootObject
{
public List<Result> results { get; set; }
}
[JsonConverter(typeof(JsonPathConverter))]
public class Result
{
[JsonProperty("phone.raw")]
public string Phone { get; set; }
[JsonProperty("accounts_balance_ach.raw")]
public decimal AccountsBalanceAch { get; set; }
[JsonProperty("accounts_balance_pending.raw")]
public decimal AccountsBalancePending { get; set; }
[JsonProperty("email.raw")]
public string Email { get; set; }
[JsonProperty("accounts_count.raw")]
public decimal AccountsCount { get; set; }
[JsonProperty("id.raw")]
public string Id { get; set; }
[JsonProperty("display_name.raw")]
public string DisplayName { get; set; }
[JsonProperty("type.raw")]
public string Type { get; set; }
[JsonProperty("advisor_email.raw")]
public string AdvisorEmail { get; set; }
[JsonProperty("created_at.raw")]
public string CreatedAt { get; set; }
[JsonProperty("source.raw")]
public string Source { get; set; }
[JsonProperty("accounts_balance.raw")]
public decimal AccountsBalance { get; set; }
[JsonProperty("accounts_donations.raw")]
public decimal AccountsDonations { get; set; }
[JsonProperty("advisor_name.raw")]
public string AdvisorName { get; set; }
[JsonProperty("_meta.score")]
public decimal MetaScore { get; set; }
}
Then you can just deserialize as usual:
var root = JsonConvert.DeserializeObject<RootObject>(json);
Here is a working demo: https://dotnetfiddle.net/wYxwIF
The Most dynamic way for you would be to use The Newtonsoft JObejct class.
It will parse your JSON string into a JSON object for you to use, this is if you do not have a corresponding model and you need to create a dynamic JSON object.
For example:
string json = "{
"meta": {
"warnings": [],
"page": {
"current": 1,
"total_pages": 1,
"total_results": 2,
"size": 10
},
"request_id": "6887a53f701a59574a0f3a7012e01aa8"
},
"results": [
{
"phone": {
"raw": 3148304280.0
},
"accounts_balance_ach": {
"raw": 27068128.71
},
"accounts_balance_pending": {
"raw": "46809195.64"
},
"email": {
"raw": "Brisa34#hotmail.com"
},
"accounts_count": {
"raw": 6.0
},
"id": {
"raw": "c98808a2-d7d6-4444-834d-2fe4f6858f6b"
},
"display_name": {
"raw": "The Johnstons"
},
"type": {
"raw": "Couple"
},
"advisor_email": {
"raw": "Cornelius_Schiller14#hotmail.com"
},
"created_at": {
"raw": "2018-10-02T10:42:07+00:00"
},
"source": {
"raw": "event"
},
"accounts_balance": {
"raw": 43629003.47
},
"accounts_donations": {
"raw": 38012278.75
},
"advisor_name": {
"raw": "Cloyd Jakubowski"
},
"_meta": {
"score": 0.42934617
}
},
{
"phone": {
"raw": 2272918612.0
},
"accounts_balance_ach": {
"raw": 35721452.35
},
"accounts_balance_pending": {
"raw": "35117465.2"
},
"email": {
"raw": "Ruby87#yahoo.com"
},
"accounts_count": {
"raw": 1.0
},
"id": {
"raw": "687af11f-0f73-4112-879c-1108303cb07a"
},
"display_name": {
"raw": "Kennith Johnston"
},
"type": {
"raw": "Individual"
},
"advisor_email": {
"raw": "Evangeline_Wisoky92#hotmail.com"
},
"created_at": {
"raw": "2018-10-02T16:16:02+00:00"
},
"source": {
"raw": "website"
},
"accounts_balance": {
"raw": 23063874.19
},
"accounts_donations": {
"raw": 33025175.79
},
"advisor_name": {
"raw": "Ernie Mertz"
},
"_meta": {
"score": 0.39096162
}
}
]
}"
JObject result = JObject.Parse(json);
result is now a JSON object and you can access it's properties.
You can use the following link to convert json to C# class. Then can use Newtonsoft Json to parse:
var jsonMessage = "{ \"meta\": { \"warnings\": [], \"page\": { \"current\": 1, \"total_pages\": 1, \"total_results\": 2, \"size\": 10 }, \"request_id\": \"6887a53f701a59574a0f3a7012e01aa8\" }, \"results\": [{ \"phone\": { \"raw\": 3148304280.0 }, \"accounts_balance_ach\": { \"raw\": 27068128.71 }, \"accounts_balance_pending\": { \"raw\": \"46809195.64\" }, \"email\": { \"raw\": \"Brisa34#hotmail.com\" }, \"accounts_count\": { \"raw\": 6.0 }, \"id\": { \"raw\": \"c98808a2-d7d6-4444-834d-2fe4f6858f6b\" }, \"display_name\": { \"raw\": \"The Johnstons\" }, \"type\": { \"raw\": \"Couple\" }, \"advisor_email\": { \"raw\": \"Cornelius_Schiller14#hotmail.com\" }, \"created_at\": { \"raw\": \"2018-10-02T10:42:07+00:00\" }, \"source\": { \"raw\": \"event\" }, \"accounts_balance\": { \"raw\": 43629003.47 }, \"accounts_donations\": { \"raw\": 38012278.75 }, \"advisor_name\": { \"raw\": \"Cloyd Jakubowski\" }, \"_meta\": { \"score\": 0.42934617 } }, { \"phone\": { \"raw\": 2272918612.0 }, \"accounts_balance_ach\": { \"raw\": 35721452.35 }, \"accounts_balance_pending\": { \"raw\": \"35117465.2\" }, \"email\": { \"raw\": \"Ruby87#yahoo.com\" }, \"accounts_count\": { \"raw\": 1.0 }, \"id\": { \"raw\": \"687af11f-0f73-4112-879c-1108303cb07a\" }, \"display_name\": { \"raw\": \"Kennith Johnston\" }, \"type\": { \"raw\": \"Individual\" }, \"advisor_email\": { \"raw\": \"Evangeline_Wisoky92#hotmail.com\" }, \"created_at\": { \"raw\": \"2018-10-02T16:16:02+00:00\" }, \"source\": { \"raw\": \"website\" }, \"accounts_balance\": { \"raw\": 23063874.19 }, \"accounts_donations\": { \"raw\": 33025175.79 }, \"advisor_name\": { \"raw\": \"Ernie Mertz\" }, \"_meta\": { \"score\": 0.39096162 } } ]}";
var message = JsonConvert.DeserializeObject<RootObject>(jsonMessage);
Console.WriteLine(message.meta.page.current); // prints 1
public class Page
{
public int current { get; set; }
public int total_pages { get; set; }
public int total_results { get; set; }
public int size { get; set; }
}
public class Meta
{
public List<object> warnings { get; set; }
public Page page { get; set; }
public string request_id { get; set; }
}
public class Phone
{
public double raw { get; set; }
}
public class AccountsBalanceAch
{
public double raw { get; set; }
}
public class AccountsBalancePending
{
public string raw { get; set; }
}
public class Email
{
public string raw { get; set; }
}
public class AccountsCount
{
public double raw { get; set; }
}
public class Id
{
public string raw { get; set; }
}
public class DisplayName
{
public string raw { get; set; }
}
public class Type
{
public string raw { get; set; }
}
public class AdvisorEmail
{
public string raw { get; set; }
}
public class CreatedAt
{
public DateTime raw { get; set; }
}
public class Source
{
public string raw { get; set; }
}
public class AccountsBalance
{
public double raw { get; set; }
}
public class AccountsDonations
{
public double raw { get; set; }
}
public class AdvisorName
{
public string raw { get; set; }
}
public class Meta2
{
public double score { get; set; }
}
public class Result
{
public Phone phone { get; set; }
public AccountsBalanceAch accounts_balance_ach { get; set; }
public AccountsBalancePending accounts_balance_pending { get; set; }
public Email email { get; set; }
public AccountsCount accounts_count { get; set; }
public Id id { get; set; }
public DisplayName display_name { get; set; }
public Type type { get; set; }
public AdvisorEmail advisor_email { get; set; }
public CreatedAt created_at { get; set; }
public Source source { get; set; }
public AccountsBalance accounts_balance { get; set; }
public AccountsDonations accounts_donations { get; set; }
public AdvisorName advisor_name { get; set; }
public Meta2 _meta { get; set; }
}
public class RootObject
{
public Meta meta { get; set; }
public List<Result> results { get; set; }
}

Cannot deserialize json data

I cannot deserialized the following data which I'm using for testing and got it from the World Bank using the following query:
http://api.worldbank.org/countries/IRL/indicators/SP.DYN.CBRT.IN?
per_page=10&date=1960:2016&format=json
[
{
"page": 1,
"pages": 28,
"per_page": "2",
"total": 56
},
[
{
"indicator": {
"id": "SP.DYN.CBRT.IN",
"value": "Birth rate, crude (per 1,000 people)"
},
"country": {
"id": "IE",
"value": "Ireland"
},
"value": "21.2",
"decimal": "0",
"date": "1961"
},
{
"indicator": {
"id": "SP.DYN.CBRT.IN",
"value": "Birth rate, crude (per 1,000 people)"
},
"country": {
"id": "IE",
"value": "Ireland"
},
"value": "21.5",
"decimal": "0",
"date": "1960"
}
]
]
My main class is called PageModel is defined as such:
public class PageModel
{
public PageModel()
{
this.List = new List<Data>();
}
[JsonProperty("page")]
public int Page { get; set; }
[JsonProperty("pages")]
public int Pages { get; set; }
[JsonProperty("per_page")]
public string PerPage { get; set; }
[JsonProperty("total")]
public int Total { get; set; }
public List<Data> List { get; set; }
}
The class used in the array is called Data and is defined as follows:
public class Data
{
public Data()
{
this.Indicator = new Indicator();
this.Country = new Country();
}
[JsonProperty("indicator")]
public Indicator Indicator { get; set; }
[JsonProperty("country")]
public Country Country { get; set; }
[JsonProperty("date")]
public int Date { get; set; }
[JsonProperty("value")]
public float Value { get; set; }
[JsonProperty("decimal")]
public decimal Decimal { get; set; }
}
Both the Country and Indicator classes are defined as follows:
public class Country
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
public class Indicator
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
My HttpClient call returns the data correctly but whenever I try to deserialize the data using the NewtonSoft JsonConvert.DeserializeObject function:
PageModel pageModel = JsonConvert.DeserializeObject<PageModel>(data);
It returns null.
Any ideas why?
Thanks.
Your JSON data is in wrong format:
Change your json to this and it will work:
{
"page": 1,
"pages": 28,
"per_page": "2",
"total": 56,
"List":[
{
"indicator": {
"id": "SP.DYN.CBRT.IN",
"value": "Birth rate, crude (per 1,000 people)"
},
"country": {
"id": "IE",
"value": "Ireland"
},
"value": "21.2",
"decimal": "0",
"date": "1961"
},
{
"indicator": {
"id": "SP.DYN.CBRT.IN",
"value": "Birth rate, crude (per 1,000 people)"
},
"country": {
"id": "IE",
"value": "Ireland"
},
"value": "21.5",
"decimal": "0",
"date": "1960"
}
]
}

json accept single value as array

How to json accept single value as array?
This json throw exception:
{
"code": "1",
"message": "OK",
"response": {
"partners":
{
"id": "33",
"name": "",
"clienttypeid": "29",
"logo": "",
"description": "",
"website": "www.site.com"
}
}
}
This json parsed correct:
{
"code": "1",
"message": "OK",
"response": {
"partners": [
{
"id": "33",
"name": "",
"clienttypeid": "29",
"logo": "",
"description": "",
"website": "www.site.com"
},
{
"id": "34",
"name": "",
"clienttypeid": "29",
"logo": "",
"description": "",
"website": "www.site.com"
}
]
} }
Model:
public class Partner
{
public string id { get; set; }
public string name { get; set; }
public string clienttypeid { get; set; }
public string logo { get; set; }
public string description { get; set; }
public string website { get; set; }
}
public class Response
{
public List<Partner> partners { get; set; }
}
public class RootObject
{
public string code { get; set; }
public string message { get; set; }
public Response response { get; set; }
}
If you're trying to deserialize to a List, use array notation, even with one element
{
"code":"1",
"message":"OK",
"response":{
"partners":[
{
"id":"33",
"name":"",
"clienttypeid":"29",
"logo":"",
"description":"",
"website":"www.site.com"
}
]
}
}
I used Json.net to convert the partners to array if it is a single object
string Normalize(string json)
{
var jobj = JObject.Parse(json);
if (!(jobj["response"]["partners"] is JArray))
{
jobj["response"]["partners"] = new JArray(jobj["response"]["partners"]);
}
return jobj.ToString();
}

Categories

Resources