Deserialize a list of objects from Json Http response - c#

I have my JSON Response like that:
{
"Adddress": [
{
"Country": "United States",
"City": "Irmo",
"Line1": "103 Kinley Rd",
"Line2": null,
"PostalCode": "20063",
"State": "SC",
"AddressCode": "BILL-01"
},
{
"Country": "United States",
"City": "Irmo",
"Line1": "1098 Kanley Road",
"Line2": "Building B",
"PostalCode": "29063",
"State": "SC",
"AddressCode": "SHIP-01"
}]
}
َAnd Here is my Address Class:
[JsonObject()]
public class Address
{
public string AddressCode { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Country { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string City { get; set; }
}
And I have this C# Code to deserialize this http response to my object list:
HttpResponseMessage response = client.GetAsync(urlParameters).Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
var dataObjects = response.Content.ReadAsAsync<Adddress>().Result;//JsonConvert.DeserializeObject<List<RestResponse>>(response.Content.ReadAsStringAsync().Result);//
foreach (var d in dataObjects)
{
Console.WriteLine("{0}", d.Country);
}
}
But I'm getting this error:
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IEnumerable`1[TestREST.Program+RestResponse]' 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 'RestResponse', line 2, position 19.
What should I do with it to make my deserilization work ?

Adddress is single, the json you get in is an array of addresses (so more then one), you have to deserialize it into e.g. AddressList that contains more then one address
string json = "{\"Adddress\":[{\"Country\":\"United States\",\"City\":\"Irmo\",\"Line1\":\"103 Kinley Rd\",\"Line2\":null,\"PostalCode\":\"20063\",\"State\":\"SC\",\"AddressCode\":\"BILL - 01\"},{\"Country\":\"United States\",\"City\":\"Irmo\",\"Line1\":\"1098 Kanley Road\",\"Line2\":\"Building B\",\"PostalCode\":\"29063\",\"State\":\"SC\",\"AddressCode\":\"SHIP - 01\"}]}";
var dataObjects = JsonConvert.DeserializeObject<AddressList>(json);
foreach (var d in dataObjects.Adddress)
{
Console.WriteLine("{0}", d.Country);
}
Classes:
public class Adddress
{
[JsonProperty("Country")]
public string Country { get; set; }
[JsonProperty("City")]
public string City { get; set; }
[JsonProperty("Line1")]
public string Line1 { get; set; }
[JsonProperty("Line2")]
public string Line2 { get; set; }
[JsonProperty("PostalCode")]
public string PostalCode { get; set; }
[JsonProperty("State")]
public string State { get; set; }
[JsonProperty("AddressCode")]
public string AddressCode { get; set; }
}
public class AddressList
{
[JsonProperty("Adddress")]
public IList<Adddress> Adddress { get; set; }
}

Related

JSON C# deserialization

I am having trouble with deserializing data from a JSON string:
[{
"Example A": [{
"Parameter1": "Example A",
"Parameter2": "aaa",
"Parameter3": "2022-06-30 21:15:00.0000000",
"Value": 11.11
}
],
"Example B": [{
"Parameter1": "Example B",
"Parameter2": "ccc",
"Parameter3": "2022-06-30 21:15:00.0000000",
"Value": 33.33
}
],
"Example C": [
{
"Parameter1": "Example C",
"Parameter2": "eee",
"TimestampUTC": "2022-06-30 21:15:00.0000000",
"Value": null
},
{
"Parameter1": "Example C",
"Parameter2": "fff",
"Parameter3": "2022-06-30 21:15:00.0000000",
"Value": 44.44
}
]
}]
What I have tried is:
public class ExampleA
{
public string Parameter1 { get; set; }
public string Parameter2 { get; set; }
public string Parameter3 { get; set; }
public double Value { get; set; }
}
public class ExampleB
{
public string Parameter1 { get; set; }
public string Parameter2 { get; set; }
public string Parameter3 { get; set; }
public double Value { get; set; }
}
public class ExampleC
{
public string Parameter1 { get; set; }
public string Parameter2 { get; set; }
public string Parameter3 { get; set; }
public double Value { get; set; }
}
public class Examples
{
[JsonProperty("Example A")]
public List<ExampleA> ExampleA { get; set; }
[JsonProperty("Example B")]
public List<ExampleB> ExampleB { get; set; }
[JsonProperty("Example C")]
public List<ExampleC> ExampleC { get; set; }
}
But when I try to test it with this:
Examples someVar = JsonConvert.DeserializeObject<Examples>(JsonString);
Console.WriteLine(SomeVar.ExampleA.Count);
I get this error:
Unhandled exception. Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MyProject.Examples' 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<T> 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.
Apparently I have trouble understanding how deserialization works - what I want to do with this is something like this:
foreach item in Example
// do something
foreach thing in item
// do something more
I realise I have some trouble with grasping the JSON format in this case.
I'm using .NET Core.
you have an array in your json Try this
List<Examples> someVar = JsonConvert.DeserializeObject<List<Examples>>(JsonString);

Json.JsonSerializationException : Cannot deserialize the current JSON object

My problem is that I'm getting this error when I try to deserialize my API json response.
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Entities.JsonDataType]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
My json data return something like this
{
"success": true,
"result": [
{
"name": "USD Amerikan Doları",
"buying": "6.6920",
"selling": "6.6995"
},
{
"name": "EUR Euro",
"buying": "7.7322",
"selling": "7.7393"
},
{
"name": "GBP İngiliz Sterlini",
"buying": "8.5933",
"selling": "8.6041"
},
"..."
]
}
My class properties:
public class JsonDataType
{
//public string name { get; set; }
//public string buying { get; set; }
//public string selling { get; set; }
public bool success { get; set; }
public List<Result> result { get; set; }
}
public class Result
{
public string name { get; set; }
public string buying { get; set; }
public string selling { get; set; }
}
And I'm getting the error when I deserialize:
List<JsonDataType> X = Newtonsoft.Json.JsonConvert.DeserializeObject<List<JsonDataType>>(response.Content);
Also I tried these codes but none of them working
JsonDataType X = JsonConvert.DeserializeObject(response.Content);
IEnumerable<Result> X = (JsonDataType)JsonConvert.DeserializeObject<IEnumerable<Result>>(response.Content, typeof(JsonDataType));
List<Result> X = JsonConvert.DeserializeObject<JsonDataType>(response.Content, typeof(Result));
If someone could help me i will be so peaceful.
Thanks for your time in advance (✿◠‿◠)
Here is my answer
JsonDataType X = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonDataType>(response.Content);

Unusual Deserialization Error from JSON to C#

.Net Fiddle 1
I have a JOSN received from external API as follows
[{
"assignedto": "MAIN STAFF",
"createduser": "API-71",
"departmentid": "1",
"observations": [{
"abnormalflag": "abnormal",
"analytename": "HGB A1C",
"value": "5"
}],
"pages": [],
"priority": "2",
"status": "REVIEW"
}]
I did a Paste Special in Visual Studio and got following classes
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string assignedto { get; set; }
public string createduser { get; set; }
public string departmentid { get; set; }
public Observation[] observations { get; set; }
public object[] pages { get; set; }
public string priority { get; set; }
public string status { get; set; }
}
public class Observation
{
public string abnormalflag { get; set; }
public string analytename { get; set; }
public string value { get; set; }
}
When I do a deserialization, I am getting following error
Run-time exception (line 24): Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Rootobject' 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.
C# Code
public static void Main(string[] args)
{
var json = #"[{
""assignedto"": ""MAIN ST (HUB) STAFF"",
""createduser"": ""API-7127"",
""departmentid"": ""1"",
""observations"": [{
""abnormalflag"": ""abnormal"",
""analytename"": ""HGB A1C"",
""value"": ""5""
}],
""pages"": [],
""priority"": ""2"",
""status"": ""REVIEW""
}]";
Rootobject resultObj = JToken.Parse(json).ToObject<Rootobject>();
}
I referred similar questions like Create a strongly typed c# object from json object with ID as the name - but that is a different issue.
Any idea how to fix this? Also what is the better way to generate C# classes from JSON?
Note: I also tried with class I got from http://json2csharp.com/. That also faield - Fidlle 2
I would use Newtonsoft / Json convert and change this:
Rootobject resultObj = JToken.Parse(json).ToObject<Rootobject>();
to:
using Newtonsoft.Json;
-- snip --
var resultObj = JsonConvert.DeserializeObject<List<Class1>>(json);
Console.WriteLine(resultObj.Count); // 1
Class1 result = resultObj[0];
Console.WriteLine(result.assignedto); // "MAIN ST (HUB) STAFF"
This will give you a collection of RootObject
As #JeffMeracdo states above - you are providing a collection of object and trying to parse as though it is a single object
As #JeffMeracdo states above, try this:
List<Example> resultObj = JsonConvert.DeserializeObject<List<Example>>(json);
Following using statement and package along with Newtonsoft.Json Nuget package:
using Newtonsoft.Json;
Classes:
public class Observation
{
public string abnormalflag { get; set; }
public string analytename { get; set; }
public string value { get; set; }
}
public class Example
{
public string assignedto { get; set; }
public string createduser { get; set; }
public string departmentid { get; set; }
public List<Observation> observations { get; set; }
public List<object> pages { get; set; }
public string priority { get; set; }
public string status { get; set; }
}

Problems Deserializing Nested JSON Array in C#

Edit
I notice this is getting negative votes, I imagine it's for not showing research effort.
I've looked at a lot of stack overflow posts. I can't find an example with JSON this heavily nested that has been accessed with examples of how the data stored in the JSON has been manipulated afterwards.
Problem and Aim
Using restsharp I've received a JSON response to an API call I made however I'm struggling to deserialize the response I'm getting. The data I want to use seems to be a nested array (below).
My aim is to then pass the contents of that array to a variable, check if it's populated, take the first item of that array, and then set the properties in that item equal to objects in my database.
This is the error message I'm getting with my current code. It seems like I'm treating the Hit object as the wrong type of object however after a few hours of banging my head against a wall I'm not entirely sure why in particular this isn't working for this particular JSON structure.
Current Code
var hitresult = JsonConvert.DeserializeObject( response.Content, typeof( List<Hit> ) ) as List<Hit>;
if (hitresult.Any())
{
var address = hitresult.FirstOrDefault();
verified = true;
result = string.Format( "UDPRN: {0}", address.udprn );
location.Street1 = address.line_1;
location.Street2 = address.line_2;
location.City = address.post_town;
location.State = address.county;
location.PostalCode = address.postcode;
Error Message
An exception of type 'Newtonsoft.Json.JsonSerializationException'
occurred in Newtonsoft.Json.dll but was not handled in user code
Additional information: Cannot deserialize the current JSON object
(e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[org.hopecorby.LocationService.Hit]'
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 'result', line 1, position 10.
Example JSON
{
"result": {
"total": 2,
"limit": 10,
"page": 0,
"hits": [
{
"dependant_locality": "",
"postcode_type": "L",
"po_box": "",
"post_town": "LONDON",
"delivery_point_suffix": "1A",
"double_dependant_locality": "",
"su_organisation_indicator": " ",
"longitude": -0.127695242183412,
"department_name": "",
"district": "Westminster",
"building_name": "",
"dependant_thoroughfare": "",
"northings": 179951,
"premise": "10",
"postcode_outward": "SW1A",
"postcode_inward": "2AA",
"sub_building_name": "",
"eastings": 530047,
"postcode": "SW1A 2AA",
"country": "England",
"udprn": 23747771,
"line_3": "",
"organisation_name": "Prime Minister & First Lord Of The Treasury",
"ward": "St James's",
"county": "",
"line_1": "Prime Minister & First Lord Of The Treasury",
"building_number": "10",
"thoroughfare": "Downing Street",
"line_2": "10 Downing Street",
"latitude": 51.5035398826274
},
{
"dependant_locality": "",
"postcode_type": "S",
"po_box": "",
"post_town": "LONDON",
"delivery_point_suffix": "1B",
"double_dependant_locality": "",
"su_organisation_indicator": " ",
"longitude": -0.122624730080001,
"department_name": "",
"district": "Camden",
"building_name": "Downing Court",
"dependant_thoroughfare": "",
"northings": 182178,
"premise": "Flat 10, Downing Court",
"postcode_outward": "WC1N",
"postcode_inward": "1LX",
"sub_building_name": "Flat 10",
"eastings": 530342,
"postcode": "WC1N 1LX",
"country": "England",
"udprn": 26245117,
"line_3": "Grenville Street",
"organisation_name": "",
"ward": "Bloomsbury",
"county": "",
"line_1": "Flat 10",
"building_number": " ",
"thoroughfare": "Grenville Street",
"line_2": "Downing Court",
"latitude": 51.5234851731108
}
]
},
"code": 2000,
"message": "Success"
}
My Models(Created with json2charp)
public class Hit
{
public string dependant_locality { get; set; }
public string postcode_type { get; set; }
public string po_box { get; set; }
public string post_town { get; set; }
public string delivery_point_suffix { get; set; }
public string double_dependant_locality { get; set; }
public string su_organisation_indicator { get; set; }
public double longitude { get; set; }
public string department_name { get; set; }
public string district { get; set; }
public string building_name { get; set; }
public string dependant_thoroughfare { get; set; }
public int northings { get; set; }
public string premise { get; set; }
public string postcode_outward { get; set; }
public string postcode_inward { get; set; }
public string sub_building_name { get; set; }
public int eastings { get; set; }
public string postcode { get; set; }
public string country { get; set; }
public int udprn { get; set; }
public string line_3 { get; set; }
public string organisation_name { get; set; }
public string ward { get; set; }
public string county { get; set; }
public string line_1 { get; set; }
public string building_number { get; set; }
public string thoroughfare { get; set; }
public string line_2 { get; set; }
public double latitude { get; set; }
}
public class Result
{
public int total { get; set; }
public int limit { get; set; }
public int page { get; set; }
public List<Hit> hits { get; set; }
}
public class RootObject
{
public Result result { get; set; }
public int code { get; set; }
public string message { get; set; }
}
The Deserializer expects a JSON Array. Your JSON is a JSON Object containing a JSON Array. There's no way the deserializer can know that you expect it to start its work with the hits array.
You need to deserialize as the RootObject. Then you would be able to refer to the List<Hit> as a property of the Result.
Update:
The following code should give you a sense of what I mean. I tested this and it works for me, with your objects and your JSON.
var sr = new StreamReader(#"C:\Users\danielc\Documents\Visual Studio 2012\Projects\TestJSON\TestJSON\response.json");
string json = sr.ReadToEnd();
sr.Close();
var root = JsonConvert.DeserializeObject<RootObject>(json);
var result = root.result;
var hits = result.hits;
if (hits.Any())
{
var address = hits.FirstOrDefault();
var udprn = string.Format("UDPRN: {0}", address.udprn);
Console.WriteLine(udprn);
}
Console.Read();

Parsing nested JSON objects with JSON.NET

My JSON feed has nested objects like this:
{
"id": 1765116,
"name": "StrozeR",
"birth": "2009-08-12",
"avatar": "http:\/\/static.erepublik.com\/uploads\/avatars\/Citizens\/2009\/08\/12\/f19db99e9baddad73981d214a6e576ef_100x100.jpg",
"online": true,
"alive": true,
"ban": null,
"level": 61,
"experience": 183920,
"strength": 25779.42,
"rank": {
"points": 133687587,
"level": 63,
"image": "http:\/\/www.erepublik.com\/images\/modules\/ranks\/god_of_war_1.png",
"name": "God of War*"
},
"elite_citizen": false,
"national_rank": 6,
"residence": {
"country": {
"id": 81,
"name": "Republic of China (Taiwan)",
"code": "TW"
},
"region": {
"id": 484,
"name": "Hokkaido"
}
}
}
and my object classes are like this:
class Citizen
{
public class Rank
{
public int points { get; set; }
public int level { get; set; }
public string image { get; set; }
public string name { get; set; }
}
public class RootObject
{
public int id { get; set; }
public string name { get; set; }
public string avatar { get; set; }
public bool online { get; set; }
public bool alive { get; set; }
public string ban { get; set; }
public string birth { get; set; }
public int level { get; set; }
public int experience { get; set; }
public double strength { get; set; }
public List<Rank> rank { get; set; }
}
}
I try to parse my JSON data with following code
private async void getJSON()
{
var http = new HttpClient();
http.MaxResponseContentBufferSize = Int32.MaxValue;
var response = await http.GetStringAsync(uri);
var rootObject = JsonConvert.DeserializeObject<Citizen.RootObject>(response);
uriTB.Text = rootObject.name;
responseDebug.Text = response;
}
but I get the following error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Erepublik.Citizen+Rank]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
I can't even parse the value in the main object. Anyway to fix this? and how can I parse a value inside of a nested object? for example: "points" in "rank"
Like the error message says, your rank property in the .NET class is a List<Rank>, but in your JSON it's just a nested object, not an array. Change it to just a Rank instead of a List<Rank>.
Arrays in JSON (or any Javascript, really) are enclosed in []. The {} characters specify a single object. The CLR type has to roughly match the JSON type in order to deserialize. Object to object, array to array.

Categories