Deserializing an array of objects with Json.Net - c#

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);

Related

Issue in Deserializing JSON Response Data to List

i having issues getting the elements in data into a list.
I want to be able to get User_ID, Country, Continent and other elements to a list after which i will do a bulk insert to the database.
The Error i get
Error Message
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in mscorlib.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[Country_API.Response]' 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.
This is the JSon Data returned from the API
{
"Status": "200 Ok",
"Message": "Data retrieved",
"Response": {
"current_page": 1,
"data": [
{
"User-ID": "EAD001",
"Country": "Ghana",
"Continent": "Africa",
"Gender": "Male",
"Email": "ead1#yahoo.com",
"Religion": ""
},
{
"User-ID": "EAD002",
"Country": "Senegal",
"Continent": "Africa",
"Gender": "Female",
"Email": "ead2#yahoo.com",
"Religion": "Muslim"
}
]
}
}
I am trying to Deserilize but it throws the above error.. this is what i am trying
if (result.IsSuccessStatusCode)
{
string toJsonString = await result.Content.ReadAsStringAsync();
var deserialize = JsonConvert.DeserializeObject<List<Response>>(toJsonString);
}
Json Model
public class Data
{
public string User-ID { get; set; }
public string Country { get; set; }
public string Continent { get; set; }
public string Gender { get; set; }
public string Email { get; set; }
public string Religion { get; set; }
}
public class Response
{
public int current_page { get; set; }
public IList<Data> data { get; set; }
}
public class Application
{
public string Status { get; set; }
public string Message { get; set; }
public Response Response { get; set; }
}
How to i achieve this please?
You're trying to deserialize the List inside the object. You need to deserialize the entire object. Try this:
if (result.IsSuccessStatusCode)
{
string toJsonString = await result.Content.ReadAsStringAsync();
var deserialize = JsonConvert.DeserializeObject<Application>(toJsonString);
IList<Data> dataList = deserialize.Response.data;
}
Issue is here . You have used "List" instead of "Response". bcoz in JSON "Response" is object not a list
var deserialize = JsonConvert.DeserializeObject<List<Response>>(toJsonString);
use like this.
var deserialize = JsonConvert.DeserializeObject<Response>(toJsonString);

How to Deserialize a JSON Array from Web API in UPW C#?

I want to connect to bitbay web api, get data JSON from there and save it to a file. My JSON looks like that:
{
"status": "Ok",
"items": [
{
"id": "737a2935-84c9-11ea-8cdc-0242ac11000e",
"t": "1587581134890",
"a": "0.00926098",
"r": "29999",
"ty": "Buy"
},
{
"id": "6c4474fa-84c9-11ea-8cdc-0242ac11000e",
"t": "1587581122794",
"a": "0.02475367",
"r": "29999",
"ty": "Buy"
}
]
}
I want to get t,a,r and ty from it. I've got code:
public class TradeModel
{
public decimal R { get; set; }
public decimal A { get; set; }
public string Ty { get; set; }
public DateTime T { get; set; }
}
public class TradeItemModel
{
public TradeModel Items { get; set; }
}
public class TradeProcessor
{
public static async Task<TradeModel> LoadTrades( int limit = 1 )
{
string url = "";
if (limit <= 300)
{
url = $"https://api.bitbay.net/rest/trading/transactions/BTC-PLN?limit={ limit }";
}
else
{
}
using (HttpResponseMessage response = await ApiHelper.ApiClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
TradeItemModel trade = await response.Content.ReadAsAsync<TradeItemModel>();
return trade.Items;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
}
After I run this code I gets an Exception:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'DemoLibrary.TradeModel' 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 'items', line 1, position 24.”
The Item in TradeItemModel class should be a collection TradeModel[] or List<TradeModel>, and you can also add Status to check it if is OK or KO:
public class TradeItemModel
{
public string Status { get; set; }
public List<TradeModel> Items { get; set; }
}
You must change also the method signature to:
public static async Task<List<TradeModel>> LoadTrades( int limit = 1 )
I hope this helps you out.

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; }
}

How to Deserialize JSON data? C#

Im getting a Json Data from an API and i have been trying to deserialize.
Json data:
{
   "items": [
      {
         "id": "1",
         "name": "samplename",
         "AddressList1": {
            "City": "Hyd",
            "State": "TN",
            "Country": "IN"
         },
         "Age": "10"
      },
      {
         "id": "2",
         "name": "samplename2",
         "AddressList1": {
            "City": "Hydd",
            "State": "TN",
            "Country": "IN"
         },
         "Age": "10"
      }
   ],
   "paging": {
      "cursors": {}
   }
}
Entities:
public class AddressList1
{
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
public class Item
{
public string id { get; set; }
public string name { get; set; }
public AddressList1 addressList1 { get; set; }
public string Age { get; set; }
}
public class Cursors
{
}
public class Paging
{
public Cursors cursors { get; set; }
}
public class Users
{
public List<Item> items { get; set; }
public Paging paging { get; set; }
}
C# code:
JsonConvert.DeserializeObject<List<Users>>(content);
Error Message:
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type 'System.Collections.Generic.List`1[Entities.Users]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly.
where am i doing wrong?
The following is a JSON-object; in your case a User
{ ... }
The following is a JSON-array; in your case an array of User
[ { ... }, { ... } ]
Thus if you want to deserialize the JSON you got into an array of Users this is not possible because you have no array in JSON.
Therefore the right code to deserialize is:
JsonConvert.DeserializeObject<Users>(content);
Furthermore your mapping is erroneous because in JSON there is a property AddressList1 and in the class it is called addressList1
Given your JSON, you would need a POCO object that contains a items member and a paging member.
JsonConvert.DeserializeObject<Users>(content);
should work.
Your Json string is good formatted and the entities are according to Json2Csharp good too.
but your problem is with the instruction JsonConvert.DeserializeObject<List<Users>>(content);
all that json that you have is only ONE User, and you are trying to get a list of them, there is the issue,
you can try instead with:
JsonConvert.DeserializeObject<Users>(content);
Try Below Code
JsonConvert.DeserializeObject<Users>(content);
Your entities(models) look just fine. If you are using, or were to use ASP.NET Web API 2, and your client is using the http verb post for example, this setup would work as Web API takes care of the object deserialization:
public HttpStatusCode Post(Item item)
{
Debug.Write(item.toString());
return HttpStatusCode.OK;
}
If you insist in deserializing manually then use the JavaScriptSerializer library which allows you to do things like:
Item item = new JavaScriptSerializer().Deserialize<Item>(content);
Notice that .Deserialize<T>() takes a generic which in your case it Item.
Hope that helps.

Converting JSON to List

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);

Categories