Converting JSON to List - c#

I am stuck in a step that I am sure should work. I have a method (in a separate class) that should return a List as its value after processing the JSON. I am going to paste the code skipping the JSON configuration stuff:
public static dynamic CustInformation(string Identifier)
{
//SKIPPED JSON CONFIG STUFF (IT'S WORKING CORRECTLY)
var result = "";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
dynamic d;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return JsonConvert.DeserializeObject<List<Models.RootObject>>(result);
}
The model was generated using C# to Json converter:
public class Record
{
public string idIdentifier { get; set; }
public string KnowName1 { get; set; }
public string KnowAddress1 { get; set; }
public string KnowRelation1 { get; set; }
public string KnowPhone1 { get; set; }
public string KnowName2 { get; set; }
public string KnowAddress2 { get; set; }
//.....skipped other variables
}
public class RootObject
{
public List<Record> record { get; set; }
}
And I am calling the method like this:
var model = Classes.EndPoint.CustInformation(identifier);
Yet I am getting this error everytime:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Models.RootObject]' 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 'record', line 1, position 10.
EDIT: JSON
{
"record": [
{
Identifier": "DQRJO1Q0IQRS",
"KnowName1": "",
"KnowAddress1": "",
"KnowRelation1": "",
"KnowPhone1": "",
"KnowName2": "",
"KnowAddress2": "",
//.....MORE STYFF
}
]
}

Like I said in the comments, and like the error message clearly states, you're trying to deserialize into a list of root objects, but your JSON is only one root object, not an array.
Here's what your C# should be.
return JsonConvert.DeserializeObject<Models.RootObject>(result);

Related

Deserializing JSON with Newtonsoft, using a specific class

I know there are lots of questions on how to do this...
I have a pretty complex JSON returned from an API and I am trying to work my way through it. I simplified the JSON answer so it holds one of the immanent problems.
The simplified JSON answer
{"data":[{"type":"task","id":"10118"},{"type":"task","id":"10004"}]}
My class to be used for the deserialisation
namespace TestJsonDeserializeApp
{
class jsonTask
{
public List<Data> data { get; set; }
public class Data
{
public string id { get; set; }
public string type { get; set; }
}
}
}
How I want to do the deserialisation
List<jsonTask> test = JsonConvert.DeserializeObject<List<jsonTask>>(strJSON);
and finally the error message I am getting
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[TestJsonDeserializeApp.jsonTask]' 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 'data', line 1, position 8.
Can one of you tell me how I have to write the jsonTask class to fit the structure of the JSON input?
Copy your JSON. Open Visual studio. Create new C# class file. Now Select below menu option:
Edit > Paste Special > Paste JSON as classes
This will create a class as below
public class Rootobject
{
public Datum[] data { get; set; }
}
public class Datum
{
public string type { get; set; }
public string id { get; set; }
}
Now change RootObject to jsonTask and deserialise as below
jsonTask test = JsonConvert.DeserializeObject<jsonTask>(strJSON);
With your code you are casting the strJSON to List with a list. You need to remove the outer list since jsonTask alreadyhas the public List data { get; set; }
Try:
jsonTask test = JsonConvert.DeserializeObject(strJSON);

How to deserialize JSON to complex object in C#

I'm trying to deserialize json result to wanted object. The result I'm getting is:
{
"base": "EUR",
"date": "2017-06-30",
"rates": {
"AUD": 1.4851,
"BGN": 1.9558,
"BRL": 3.76,
"CAD": 1.4785
}
}
I want this result to deserialize to my object:
public class ExchangeRates
{
public string Base { get; set; }
public DateTime Date { get; set; }
public IList<Rates> Rates { get; set; }
}
public class Rates
{
public string Name { get; set; }
public decimal Value { get; set; }
}
my deserialization looks like this:
using (var httpClient = new HttpClient())
{
var response = httpClient.GetAsync("http://api.fixer.io/latest").Result;
var result = response.Content.ReadAsStringAsync().Result;
var values = JsonConvert.DeserializeObject<ExchangeRates>(result);
}
When I run the program I get following exception:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ConsoleApp4.Rates]' 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 'rates.AUD', line 1, position 49.'
How can I deserialize JSON to my wanted object??
UPDATE 1
Or maybe I can just deserialize 'rates' list?
Take a look at your JSON, specifically rates:
"rates": {
"AUD": 1.4851,
"BGN": 1.9558,
"BRL": 3.76,
"CAD": 1.4785
}
This is very clearly a JSON object, as it has key-value pairs. However, looking at your code, you have defined the corresponding property (Rates) as an IList:
public IList<Rates> Rates { get; set; }
I understand your reasoning behind defining the Rates class. You think that by defining that class, NewtonSoft will deserialize rates the way you want it to. However, this is impossible because rates is not an array, and therefore deserializing it into any kind of IList is impossible.
The easiest and most clear cut solution is to use a dictionary:
public Dictionary<string, decimal> Rates { get; set; }
However, if you don't want to use a dictionary, you need to modify your JSON like so and your solution will work:
"rates":[
{
"Name":"AUD",
"Value":1.4851
},
{
"Name":"BGN",
"Value":1.9558
},
{
"Name":"BRL",
"Value":3.76
},
{
"Name":"CAD",
"Value":1.4785
}
]
By converting rates to an array, and making its contents objects instead of key-value pairs, NewtonSoft can deserialize rates as a list, and its contents as instances of the Rates class.
I agree with the other guys comments: you should use a Dictionary. To achieve the conversion to your final object structure you can use for example an intermediary class with an explicit cast operator.
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
public class Program
{
public void Main()
{
var result = #"{
""base"": ""EUR"",
""date"": ""2017-06-30"",
""rates"": {
""AUD"": 1.4851,
""BGN"": 1.9558,
""BRL"": 3.76,
""CAD"": 1.4785
}}";
var values = (ExchangeRates) JsonConvert.DeserializeObject<TempExchangeRates>(result);
Console.WriteLine(values.Base);
Console.WriteLine(values.Date);
foreach(var rate in values.Rates)
Console.WriteLine(rate.Name + ": " + rate.
}
}
public class TempExchangeRates
{
public string Base { get; set; }
public DateTime Date { get; set; }
public Dictionary<string,decimal> Rates { get; set; }
public static explicit operator ExchangeRates(TempExchangeRates tmpRates)
{
var xRate = new ExchangeRates();
xRate.Base = tmpRates.Base;
xRate.Date = tmpRates.Date;
xRate.Rates = new List<Rates>();
foreach(var de in tmpRates.Rates)
xRate.Rates.Add(new Rates{Name = de.Key, Value = de.Value});
return xRate;
}
}
public class ExchangeRates
{
public string Base { get; set; }
public DateTime Date { get; set; }
public IList<Rates> Rates { get; set; }
}
public class Rates
{
public string Name { get; set; }
public decimal Value { get; set; }
}

Newtonsoft JSON Deserialize Issue [Error converting value to type]

Utilizing C# Newtownsoft JSON libraries... I have run into this issue.
To set the stage...
I have this JSON from a RESTful Web Service:
[
{
"CorporateArea": "Brampton",
"ServiceAddress": "321 Heart Lake Road",
"VendorName": "Enbridge Gas Distribution Inc",
"MeterNumber": "502105",
"RateClass": "NG-R6",
"Department": "22603",
"Account": "12008",
"VendorID": "0000001195",
"MeterLevelID": 2882,
"SiteAddressID": 468,
"MappingLocation": "Beckett Sproule",
"ElectricalBilling": "",
"EnergyLine": "",
"CorporateGroup": "Public Works"
}
]
I also have these C# classes:
public class AccountInfo
{
[JsonProperty("Account")]
public string Account { get; set; }
[JsonProperty("CorporateArea")]
public string CorporateArea { get; set; }
[JsonProperty("CorporateGroup")]
public string CorporateGroup { get; set; }
[JsonProperty("Department")]
public string Department { get; set; }
[JsonProperty("ElectricalBilling")]
public string ElectricalBilling { get; set; }
[JsonProperty("EnergyLine")]
public string EnergyLine { get; set; }
[JsonProperty("MappingLocation")]
public string MappingLocation { get; set; }
[JsonProperty("MeterLevelID")]
public string MeterLevelID { get; set; }
[JsonProperty("MeterNumber")]
public string MeterNumber { get; set; }
[JsonProperty("RateClass")]
public string RateClass { get; set; }
[JsonProperty("ServiceAddress")]
public string ServiceAddress { get; set; }
[JsonProperty("SiteAddressID")]
public string SiteAddressID { get; set; }
[JsonProperty("VendorID")]
public string VendorID { get; set; }
[JsonProperty("VendorName")]
public string VendorName { get; set; }
}
public class JSONArray {
public IList<AccountInfo> AccountsInfo { get; set; }
}
From these, I call this Newtownsoft Method:
JSONArray Accounts = JsonConvert.DeserializeObject<JSONArray> (responseBody,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
But everytime I do so, I get the exception Newtonsoft.Json.JsonSerializationException
with the error message:
Error converting value "[{"CorporateArea":"Brampton","ServiceAddress":"321 Heart Lake Road","VendorName":"Enbridge Gas Distribution Inc","MeterNumber":"502105","RateClass":"NG-R6","Department":"22603","Account":"12008","VendorID":"0000001195","MeterLevelID":2882,"SiteAddressID":468,"MappingLocation":"Beckett Sproule","ElectricalBilling":"","EnergyLine":"","CorporateGroup":"Public Works"}]" to type 'TestWebService_Consume.JSONArray'. Path '', line 1, position 421.
I've tried messing with the JSON string so it's not an array, and casting it into a simple AccountsInfo object, it returns the same error.
I must be doing something wrong, but it's been some time since I've worked with the Newtonsoft JSON libraries, so I'm at a loss of what could possible be the issue here.
The Deserialization output for the JSON is when trying with
JSONArray Accounts = JsonConvert.DeserializeObject<JSONArray>(json, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
is
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'JustSO.JSONArray' 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.
But if you try like this
List<AccountInfo> lc = JsonConvert.DeserializeObject<List<AccountInfo>>(json, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
or
List<AccountInfo> lc = JsonConvert.DeserializeObject<List<AccountInfo>>(json);
will give you the resultant json into Object.
Your JSOn is not an object, but an array of objects, so you don't need a class to wrap the array, you should deserialize directly to array:
var Accounts = JsonConvert.DeserializeObject<List<AccountInfo>>(responseBody,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
If you really want to have JSONArray object, you could create it and serialize to it's property. Just to mention: your AccountInfo property is private, you should change it to public to deserialize to it.
JSONArray Accounts = new JSONArray
{
AccountsInfo = JsonConvert.DeserializeObject<List<AccountInfo>>(responseBody,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
})
};
I use Newtonsoft.Json in generic read and write methods for Excel spreadsheets. Had this exception start throwing, and turned out to be a change made to the excel spreadsheet. In general column types, the first cell is used to set the data table type, generally with a header column this ends up being a string. The excel I was trying to load had a new row added at the top for zero indexing, so all columns were being set as system.double.
Just thought I'd throw that here, since it took a while to track down why this error started happening after years of working perfectly.

Deserializing an array of objects with Json.Net

The received data is like this:
Inside each item, there is an object, customer, I have an identical class for that. How can I convert them using Json.net?
I have tried the followings:
var data = JsonConvert.DeserializeObject<List<customer>>(val);
and adding another class:
public class customerJson
{
public Customer customer{ get; set; }
}
And trying to deserialize it:
var data = JsonConvert.DeserializeObject<List<customerJson>>(val);
With both of them I get an exception:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[customer]' 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 'rows', line 1, position 8.
Data:
{"rows":[{"id":"232333","name":"nam"},{"id":"3434444","name":"2ndName"}]}
If I read your json data structure correctly you would want this:
public class Root
{
public List<Customer> rows { get; set; }
}
and
var data = JsonConvert.DeserializeObject<Root>(val);
Tested code:
void Main()
{
var test = JsonConvert.DeserializeObject<Root>("{\"rows\":[{\"id\":\"232333\",\"name\":\"nam\"},{\"id\":\"3434444\",\"name\":\"2ndName\"}]}");
Console.WriteLine(test.rows[0].id); // prints 232333
}
public class Customer
{
public int id { get; set; }
}
public class Root
{
public List<Customer> rows { get; set; }
}
Just in case anyone is still having issues. This worked out for me:
If the Json looks something like this:
"result": [
{
"firstname": "John",
"lastname": "Doe",
},
{
"firstname": "Max",
"lastname": "Mustermann",
}
]
ResultList.cs
public class ResultList {
[JsonProperty("result")]
public List<ResultObj> ResultObj { get; set }
}
ResultObj.cs
public class ResultObj {
[JsonProperty("firstname")]
public string FirstName { get; set; }
[JsonProperty("lastname")]
public string LastName{ get; set; }
}
And finally:
using Newtonsoft.Json;
var resultList = JsonConvert.DeserializeObject<ResultList>(jsonString);

Cannot deserialize the current JSON object (e.g. {"name":"value"})

Please Help me out i am new in xamarin.forms and C# i have try every solution which is given in stackoverflow but cannot avail to solve
using (var httpClient = new HttpClient())
{
var response = httpClient.GetAsync(Url).Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
string contents = await responseContent.ReadAsStringAsync();
List<abcModel> tm = JsonConvert.DeserializeObject<List<abcModel>>(contents);
abcMaster = new ObservableCollection<SummaryModel>();
var c = tm[0].SSum.Count();
}
}
Model
public class abcModel
{
public List<SSum> SSum { get; set; }
}
public class SSum
{
public string Name{ get; set; }
}
My Json
{"a":[{"SSum":[{"Name":"Earth"}]}]}
Error:-
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[abcModel]' 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.
Because you obviously just want to deserialize a nested part of your json, do it like this:
var result = JsonConvert.DeserializeObject<Dictionary<string, List<abcModel>>>(json);
You're missing the a property in your JSON. You can deserialize into a class that has that property:
public class MyType
{
public List<abcModel> A { get; set; }
}
JsonConvert.DeserializeObject<MyType>(json);
Or skip that property all together (#stefankmitph's answer works well), here's another alternative:
JObject obj = JObject.Parse(json);
List<abcModel> model = obj["a"].ToObject<List<abcModel>>();
Just a note: normally C# classes are PascalCased.
If you already have the JSON string you should use a generator like json2csharp to create the response DTO. This will prevent mistakes in what is a collection versus single object.
public class SSum
{
public string Name { get; set; }
}
public class A
{
public List<SSum> SSum { get; set; }
}
public class RootObject
{
public List<A> A { get; set; }
}
Now you can deserialize the complete object:
tm = JsonConvert.DeserializeObject<RootObject>(contents);

Categories