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);
Related
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.
i'm trying to return a list of users from our software and format the names and email addresses of these users into a list so can compare this to other lists and determine what is more accurate. i'm making the request using the code below.
Question: How do I format my code to accept a json array as the error message states?
public void MakeCall()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(Url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(_urlParameters).Result;
if (response.IsSuccessStatusCode)
{
var dataObjects = response.Content.ReadAsAsync<IEnumerable<WorkfrontDataObjects>>().Result;
foreach (var workfrontData in dataObjects)
{
Console.WriteLine("{0}", workfrontData.Email);
}
}
Console.ReadLine();
}
public class WorkfrontDataObjects
{
public string[] Email { get; set; }
public string[] Name { get; set; }
public WorkfrontDataObjects()
{
}
}
Error Message:
JsonSerializationException: Cannot deserialize the current JSON object
(e.g. {"name":"value"}) into type
'System.Collections.Generic.IEnumerable`1[ManageWorkfrontADUserDistros.WorkfrontDataObjects]'
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.
UPDATE, adding json:
{
"data": [
{
"ID": "000000000000000000000000000000",
"name": "name",
"objCode": "USER",
"emailAddr": "email"
},
{
"ID": "000000000000000000000000000000",
"name": "name",
"objCode": "USER",
"emailAddr": "email"
},
2500 of whats above with obviously real data
Given your JSON, your model needs to look like this:
public class RootObject
{
[JsonProperty("data")]
public List<Item> Data { get; set; }
}
public class Item
{
[JsonProperty("ID")]
public string ID { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("objCode")]
public string ObjCode { get; set; }
[JsonProperty("emailAddr")]
public string Email { get; set; }
}
You can rename the classes and properties to suit your needs without affecting the deserialization, as long as the names in the [JsonProperty] attributes match the JSON.
Then you should be able to receive the data like this:
if (response.IsSuccessStatusCode)
{
var rootObject = response.Content.ReadAsAsync<RootObject>().Result;
foreach (var item in rootObject.Data)
{
Console.WriteLine(item.Email);
}
}
Your string[] should be string in WorkfrontDataObjects and email should be emailAddr
I can't convert JSON Object into C# class object I've tried many things but the same error pops up:
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type
'System.Collections.Generic.List`1[CoderwallDotNet.Api.Models.Account]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly.
I am using this JSON and tring to get the response in windows 8.1 application.
[
{
"id": 1,
"time": 40,
"srcLong": 35.909124,
"srcLat": 31.973628,
"destLong": 35.898258,
"destLat": 31.985622,
"subSites": [
{
"id": 1,
"name": "location1"
},
{
"id": 2,
"name": "location2"
},
{
"id": 3,
"name": "locaion3"
}
]
}]
and the I tried to read from the JSON using webclient but its not working it can't recognize it so I am using Newtonsoft.Json and I creted these class to get the response.
public class SubSite
{
public int id { get; set; }
public string name { get; set; }
}
public class RootObject
{
public int id { get; set; }
public int time { get; set; }
public double srcLong { get; set; }
public double srcLat { get; set; }
public double destLong { get; set; }
public double destLat { get; set; }
public List<SubSite> subSites { get; set; }
}
var serviceUri = "http://localhost:24728/api/sites";
var client = new HttpClient();
var response = await client.GetAsync(serviceUri);
var datafile = await response.Content.ReadAsStringAsyn();
List<RootObject> data = JsonConvert.DeserializeObject<List<RootObject>>(datafile);
test1234.Text = data.ToString();//i am trying to for eample destlat
but I can't get the value I am getting the response and everything is fine but idk how to put it into object and use it where ever I want. For example, I want to get the value of time and the other but I have problem with List of subsites or get the location inside the subsites or srclong or srclat and here is the project how to get the Json to c# object:
https://onedrive.live.com/?cid=e648f5a0f179f346&id=E648F5A0F179F346%218429&ithint=folder,rar&authkey=!ALKlJdwsb8ER2FA
This works fine:
var data = JsonConvert.DeserializeObject<RootObject>(datafile)
You can deserialize into a dynamic object if you are not too particular about losing intellisense. One advantage to using a dynamic is that you don't have to create classes just to be able to deserialize and also that you don't need to update your class structures if the returned data has changed. As an example you can do this:
dynamic jsonValue = JsonConvert.DeserializeObject(jsonData);
foreach (dynamic rootObject in jsonValue)
{
theData.destLong.Value <-- use it anyway you want, store in a variable, etc.
// to get to each of the subSite in the rootObject
foreach (dynamic subSite in rootObject.subSites)
{
subSite.id.Value <-- returns an int based on your data
subSite.name.Value <-- returns a string based on your data
}
}
// where jsonData constains the json string you posted
The foreaeach is important because the data you posted will result into an array. You can also just do a jsonValue[0] but watch out for errors for null values, which you should be checking anyway starting with the returned json string.
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);
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);