this is the json file:
{
"Message": {
"Code": 200,
"Message": "request success"
},
"Data": {
"USD": {
"Jual": "13780",
"Beli": "13760"
}
},
"LastUpdate": "2015-11-27 22:00:11",
"ProcessingTime": 0.0794281959534
}
I have a problem when I am converting to class like this:
public class Message
{
public int Code { get; set; }
public string Message { get; set; }
}
public class USD
{
public string Jual { get; set; }
public string Beli { get; set; }
}
public class Data
{
public USD USD { get; set; }
}
public class RootObject
{
public Message Message { get; set; }
public Data Data { get; set; }
public string LastUpdate { get; set; }
public double ProcessingTime { get; set; }
}
and when I deserialized with this code :
private void button1_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
var json = wc.DownloadString(textBox1.Text);
List<User> users = JsonConvert.DeserializeObject<List<User>>(json);
dataGridView1.DataSource = json;
}
When I run the code I get an unhandled exception which says:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WindowsFormApp.EmployeeInfo+Areas]' 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.”
Can anyone tell me what I am doing wrong and how to get the last item deserialized correctly?
JSON.Net is expecting (when you pass a collection type to the DeserializeObject method), that the root object is an array. According to your data, it's an object and needs to be processed as a singular user.
And then you need to pass that to the dataSource, so you'd then wrap the deserialized User into var userList = new List<User>{user};
The error message is pretty straightforward. You are trying to deserialize something that isn't an array (your JSON string) into a collection (List<User>). It's not a collection so you can't do that. You should be doing something like JsonConvert.DeserializeObject<RootObject>(json) to get a single object.
Related
I get such JSON and want to deserialize it into my C# object. But this ends up in an error that cannot deserialize. Can I get help in fixing this?
public class UserDto {
public string Id { get; set; }
public string Name { get; set; }
public List<string> Permissions { get; set; }
}
Above is the model object for binding the API output
HttpResponseMessage response = await client.GetAsync($"/users");
if (!response.IsSuccessStatusCode || response.Content == null) {
return null;
}
string result = await response.Content.ReadAsStringAsync();
UserDto users = await response.Content.ReadAsJsonAsync<UserDto>();
List<UserDto> x2 = JsonConvert.DeserializeObject<List<UserDto>>(result);
The above getasync method gives me the below result and i am trying to deserialize it to object.
{
"users": [{
"id": "1",
"name": "ttest",
"permissions": [
"add",
"edit",
"delete"
]
}]
}
Error:
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type 'System.Collections.Generic.List`1[****.Models.UserDto]'
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.
I get such JSON and want to deserialize it into my C# object. But this ends up in an error that cannot deserialize. Can I get help in fixing this?
In your JSON, Users JArray is inside a JObject, so to convert your JSON string you need List<User> inside a RootObject class like,
public class User
{
public string id { get; set; }
public string name { get; set; }
public List<string> permissions { get; set; }
}
public class Root
{
public List<User> users { get; set; }
}
Deserialize like,
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(result);
.NETFIDDLE
I am implementing a system for GPS Tracking, through the consumption of a web service api.
ERROR :
An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'TrackingRequest.Devices' 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.
This is in a web form application in c# with HttpClient using json of Newtonsoft.
My code
using (HttpClient clientKey = new HttpClient())
{
clientKey.BaseAddress = new Uri("http://api.trackingdiary.com/");
clientKey.DefaultRequestHeaders.Add("Hive-Session", key);
clientKey.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage responseKey = clientKey.GetAsync("/v2/geo/devices/list").Result;
using (HttpContent contentkey = responseKey.Content)
{
Task<string> resultKey = contentkey.ReadAsStringAsync();
Devices obj = JsonConvert.DeserializeObject<Devices>(resultKey.Result);
Console.WriteLine();
}
}
My Class:
class position
{
[JsonProperty("lat")]
public int lat { get; set; }
[JsonProperty("lng")]
public int lng { get; set; }
[JsonProperty("hdop")]
public int hdop { get; set; }
[JsonProperty("fix")]
public bool fix { get; set; }
}
class Devices
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("date_contacted")]
public string date_contacted { get; set; }
[JsonProperty("startup")]
public string startup { get; set; }
[JsonProperty("position")]
public position position { get; set; }
}
}
I want in objects to perform in DataTable.
JSON EXAMPLE
JSON EXAMPLE
It looks like your JSON string contains an array of objects of the type in question. You are trying to deserialize it into a single instance, hence the error.
Try this:
IEnumerable<Devices> devices = JsonConvert.DeserializeObject<IEnumerable<Devices>>(resultKey.Result);
And please rename the class to singular since it appears to represent a single Device.
I am using an API that returns me the result JSON formatted like this:
{
"undefined":{
"theresult":{
"back_1s":{
"consumed":1115287.58,
"min_cons":28789,
"max_cons":1086498.58,
"totalobjs":12683,
"totalproces":4298
},
"back_10s":{
"consumed":1115287.58,
"min_cons":28789,
"max_cons":1086498.58,
"totalobjs":12683,
"totalproces":4298
}
}
}
}
The first thing I did was creating a C# object that has 5 properties for each of the JSON's values.
Then I de-serialized the JSON string into an array of this new object.
However I have no idea what back_1s is, and what it will represent in C#,not to mention theresult and the undefined.
I just see no way for me to de-serialize it without help.
This is how I de-serialize in C#
List<NEWOBJECT> gooddata = JsonConvert.DeserializeObject<List<NEWOBJECT>>(jsonstring);
EDIT #1:
I am getting this error when I deserialize in C#
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'mvcAndrew.Controllers.NEWOBJECT[]' 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.
Easiest ist to generate the C# Classes from JSON:
http://json2csharp.com/
If you deserialize it use the generated RootObject class (or rename the class) that should do the trick.
This will generate two classes for Back1s / Back10s - you can still use only one class (delete the other one) and edit the "Theresult" class corresponding (for example, I renamed Back1s to BackClass and deleted the Back10s class)
public class Theresult
{
public BackClass back_1s { get; set; }
public BackClass back_10s { get; set; }
}
You can also use Newtonsoft.json.
var files = JObject.Parse(YourJsonHere);
var recList = files.SelectToken("$..theresult").ToList();
foreach (JObject item in recList.Children())
{
string values = item["consumed"].ToString();
// You can get other values here
}
Need to create a class structure same as your return object may be kind of
public class backDetails
{
public double consumed { get; set; }
public double min_cons { get; set; }
public double max_cons { get; set; }
public double totalobjs { get; set; }
public double totalproces { get; set; }
}
public class TheResult
{
public backDetails back_1s { get; set; }
public backDetails back_10s { get; set; }
}
public class MyClass
{
public TheResult theresult { get; set; }
}
Then this will work
List<MyClass> gooddata = JsonConvert.DeserializeObject<List<MyClass>>(jsonstring);
I am getting following JSON data
[{"id":"1","text":"System Admin","target":{"jQuery1710835279177001846":12},"checked":true,"state":"open"},
{"id":"2","text":"HRMS","target":{"jQuery1710835279177001846":34},"checked":false,"state":"open"},
{"id":"3","text":"SDBMS","target":{"jQuery1710835279177001846":42},"checked":false},
{"id":"8","text":"Admin","target":{"jQuery1710835279177001846":43},"checked":false},
{"id":"9","text":"My test Admin","target":{"jQuery1710835279177001846":44},"checked":false,"state":"open"},
{"id":"24","text":"ModuleName","target":{"jQuery1710835279177001846":46},"checked":false,"state":"open"}]
which try to parsed using Json.Net using strongly type
this are my property class
public class testclass
{
public string id { get; set; }
public string text { get; set; }
public string #checked { get; set; }
public string state { get; set; }
public target jQuery1710835279177001846 { get; set; }
}
public class testclass2
{
public List<testclass> testclass1 { get; set; }
}
public class target
{
public string jQuery1710835279177001846 { get; set; }
}
and here i am trying to access the data i am getting exception
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'QuexstERP.Web.UI.Areas.SysAdmin.Controllers.testclass' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
My controller code look like
public void Test(string Name, object modeldata)
{
var obj = JsonConvert.DeserializeObject<testclass>(Name);
}
Any idea how to solve this issue in C#
Your Json string looks to have serialized array object in it because it contains [ ]. It means you have a Json string which is formed after serialization of array object. So you need to deserialized into array object, so try this
var obj = JsonConvert.DeserializeObject<List<testclass>>(jsonString);
you have Array of TestClass. so it should be like this.
var model= JsonConvert.DeserializeObject<List<testclass>>(Name);
why you are using JSonConvert ? in MVC3 you can do like this
return Json(yourmodel,JsonRequestBehavior.AllowGet);
Your json objects are like this
{
"id":"1",
"text":"System Admin",
"target":{
"jQuery1710835279177001846":12
},
"checked":true,
"state":"open"
}
It should be like this I guess
{
"id":"1",
"text":"System Admin",
"jQuery1710835279177001846":12,
"checked":true,
"state":"open"
}
I have a Json like this :
[{"id":"54718","title":"Khaleda to visit China","corres":"Special Correspondent","details":"DHAKA: On a 7-day visit, opposition BNP Chairperson Khaleda Zia will leave Dhaka for China on October 14.","photo":"2012October\/SM\/Khaleda-new-sm20121003132805.jpg"}]
To parse this Json , so far I have done :
public class Attributes
{
[JsonProperty("id")]
public string ID{ get; set; }
[JsonProperty("title")]
public string TITLE { get; set; }
[JsonProperty("corres")]
public string CORRES { get; set; }
[JsonProperty("details")]
public string DETAIL { get; set; }
[JsonProperty("photo")]
public string LINK { get; set; }
}
public class DataJsonAttributeContainer
{
public List<Attributes> NewsList{ get; set; }
//public Attributes attributes { get; set; }
}
public static T DeserializeFromJson<T>(string json)
{ //I'm getting the error here
T deserializedProduct = JsonConvert.DeserializeObject<T>(json);
return deserializedProduct;
}
& In my code :
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//parse data
var container = DeserializeFromJson<DataJsonAttributeContainer>(e.Result);
//load into list
for (i = 0; i < container.NewsList.Count ; i++)
{
newData[i] = new data();
newData[i].id = container.NewsList[i].ID;
newData[i].title = container.NewsList[i].TITLE;
newData[i].price = container.NewsList[i].CORRES;
newData[i].image = container.NewsList[i].DETAIL;
newData[i].link = container.NewsList[i].LINK;
}
The Problem is : container is getting the json from web server which I can see at debugger , but it's shoeing an exception while deserializing . Can anybody help please ?
The Exception I'm getting :
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'BanglaNewsPivot.MainPage+DataJsonAttributeContainer' 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.Path '', line 1, position 1.
Your json is an array (not a single object containing array). Calling your DeserializeFromJson as below
var attrs = DeserializeFromJson<List<Attributes>>(e.Result);
is enough.
--EDIT--
foreach (var attr in attrs)
{
Console.WriteLine("{0} {1}", attr.ID, attr.TITLE);
}