I am trying to serialize a object defined below. This happens correctly using Newtonsoft JsonConvert. This returns a string.
When i try to deserialize the string back into the defined object it doesn't work and throws exception
private class PlotSetFeatureStateInfo
{
public IDictionary<int,IDictionary<AxisTypeAndUnitInfo,ManualScaleInfo>> PersistentScaleInfo
{
get;
set;
}
public IDictionary<Guid,ScaleType> PlotIdVsLocalScaleType { get; set; }
public IDictionary<Guid,IDictionary<AxisTypeAndUnitInfo,
PlotScales.PersistentScaleData>> PlotIdVsPersistentScaleData { get; set;}
}
var foo = new FeatureStateInfo
{
//Fill values
};
var res = JsonConvert.SerializeObject(foo);
var deserializedProperty = JsonConvert.DeserializeObject<FeatureStateInfo>(res);//Throws error
Getting the below error
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'System.Collections.Generic.IDictionary2[System.Int32,System.Collections.Generic.IDictionary2[Axis,ManualScale]]'
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
Posting the sample JSON without any edits. This is a valid json.
{"PersistentScaleInfo":[{"Key":1,"Value":[{"Key":{"AxisType":0,"UnitInfo":{"UnitId":"601988e7-06a1-4dfd-9bba-535989b3afba","SubunitId":"00000000-0000-0000-0000-000000000000"}},"Value":{"Units":"Hz ","MaxScale":400,"MinScale":0.062,"IsAuto":false,"Axes":"X","AxisType":0,"UnitInfo":{"UnitId":"601988e7-06a1-4dfd-9bba-535989b3afba","SubunitId":"00000000-0000-0000-0000-000000000000"},"IsMinLessThanMax":true}},{"Key":{"AxisType":1,"UnitInfo":{"UnitId":"250f1aea-b8e3-4a4d-98e0-f60abded10a4","SubunitId":"94d2baf0-3bc0-41f7-b207-d8ce54e65e35"}},"Value":{"Units":"in/s rms","MaxScale":0.015,"MinScale":0,"IsAuto":false,"Axes":"Y","AxisType":1,"UnitInfo":{"UnitId":"250f1aea-b8e3-4a4d-98e0-f60abded10a4","SubunitId":"94d2baf0-3bc0-41f7-b207-d8ce54e65e35"},"IsMinLessThanMax":true}}]}],"PlotIdVsLocalScaleType":[{"Key":"5ef394a9-98ad-4f52-b916-b698ae4ef351","Value":2}],"PlotIdVsPersistentScaleData":[{"Key":"5ef394a9-98ad-4f52-b916-b698ae4ef351","Value":[{"Key":{"AxisType":0,"UnitInfo":{"UnitId":"601988e7-06a1-4dfd-9bba-535989b3afba","SubunitId":"00000000-0000-0000-0000-000000000000"}},"Value":{"ManualScaleRange":{"MaxScale":400,"MinScale":0.062},"IsVisibleOnView":true,"IsAutoChecked":false,"AreManualScalesSet":true}},{"Key":{"AxisType":1,"UnitInfo":{"UnitId":"250f1aea-b8e3-4a4d-98e0-f60abded10a4","SubunitId":"94d2baf0-3bc0-41f7-b207-d8ce54e65e35"}},"Value":{"ManualScaleRange":{"MaxScale":0.015,"MinScale":0},"IsVisibleOnView":true,"IsAutoChecked":false,"AreManualScalesSet":true}}]}]}
SOLUTION:
i modified the class according to everyones suggestion as below.
This works fine for me
public class PlotSetFeatureStateInfo
{
public List<KeyValuePair<int, List<KeyValuePair<AxisTypeAndUnitInfo, ManualScaleInfo>>>> PersistentScaleInfo
{
get;
set;
}
public List<KeyValuePair<Guid, ScaleType>>PlotIdVsLocalScaleType { get; set; }
public List<KeyValuePair<Guid,List<KeyValuePair<AxisTypeAndUnitInfo,
PlotScales.PersistentScaleData>>>> PlotIdVsPersistentScaleData { get; set; }
}
Thank you :)
Related
I am getting JSON string request from the server side. That part not handling by my self. They send the request as following (policyJson)
{"Data":"[{\"NAME\":\"BOARD OF INVESTMENT OF SRI LANKA\",\"STARTDATE\":\"\\\/Date(1584210600000)\\\/\",\"ENDDATE\":\"\\\/Date(1615660200000)\\\/\",\"SCOPE\":\"As per the standard SLIC \\\"Medical Expenses\\\" Policy Wordings\",\"DEBITCODENO\":1274}]","ID":200}
Then I Deserialize using
BV_response _res_pol = JsonConvert.DeserializeObject<BV_response>(policyJson);
Class BV_response
public class BV_response
{
public int ID { get; set; }
public string Data { get; set; }
}
Then
string res = _res_pol.Data.Replace("\\", "");
var policyDetails = JsonConvert.DeserializeObject<PolicyData>(res);
Class PolicyData
public class PolicyData
{
public string NAME { get; set; }
public DateTime STARTDATE { get; set; }
public DateTime ENDDATE { get; set; }
public string SCOPE { get; set; }
public int DEBITCODENO { get; set; }
}
For this JSON string I am getting following exception in this line
var policyDetails = JsonConvert.DeserializeObject(res);
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'SHE_AppWS.Models.PolicyData' 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.
This is valid JSON, and does not need string manipulation. It's just JSON stored within JSON.
Do not try unescaping JSON yourself. If the JSON is not valid, get it fixed at source.
Your problem is that you are deserializing the inner JSON to a single object, but it is an array.
Instead, deserialize to a List<> or array.
BV_response _res_pol = JsonConvert.DeserializeObject<BV_response>(policyJson);
var policyDetails = JsonConvert.DeserializeObject<List<PolicyData>>(_res_pol.Data);
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.
This question already has answers here:
Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly
(6 answers)
Closed 4 years ago.
I am try to serialize the JSON with the JsonConvert library but i am getting error:
JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'APIConsume.Models.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.
The JSON which I am getting is:
[{"id":0,"name":"Alice","image":"alice.jpg","fromLocation":"New York","toLocation":"Beijing"},{"id":1,"name":"Bob","image":"bob.jpg","fromLocation":"New Jersey","toLocation":"Boston"},{"id":2,"name":"Joe","image":"joe.jpg","fromLocation":"London","toLocation":"Paris"}]
My code line giving error is:
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(apiResponse);
The RootObject class is generated by http://json2csharp.com/:
public class RootObject
{
public int id { get; set; }
public string name { get; set; }
public string image { get; set; }
public string fromLocation { get; set; }
public string toLocation { get; set; }
}
Please help?
Try this:
var rootObject = JsonConvert.DeserializeObject<List<RootObject>>(apiResponse);
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);
Question Background:
I'm using Newtonsofts JSON.NET to desearlize an XML response from a AWS service to a C# object strcuture.
The Issue:
I'm receiving the following error message when trying to deserialize on the ImageSet class Category property :
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ShoppingComparisonEngine.AWS.AWSRootListPriceObject.ImageSet]' 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 'Items.Item[1].ImageSets.ImageSet.Category', line 1, position 12122.
I should add I have no control over the returned XML and in turn have no control over the large object structure I need to deserialize the response into.
The Code:
var awsPriceLostModel = JsonConvert.DeserializeObject<AwsListPriceRootObject>(fullyEscapedData);
The following is the C# class model for 'ImageSet'
public class ImageSets
{
[JsonProperty("imageset")]
public List<ImageSet> ImageSet { get; set; }
}
public class ImageSet
{
[JsonProperty("category")]
public string Category { get; set; }
[JsonProperty("swatchimage")]
public SwatchImage SwatchImage { get; set; }
[JsonProperty("smallimage")]
public SmallImage2 SmallImage { get; set; }
[JsonProperty("thumbnailimage")]
public ThumbnailImage ThumbnailImage { get; set; }
[JsonProperty("tinyimage")]
public TinyImage TinyImage { get; set; }
[JsonProperty("mediumimage")]
public MediumImage2 MediumImage { get; set; }
[JsonProperty("largeimage")]
public LargeImage2 LargeImage { get; set; }
}
This a screenshot showing the JSON response with the Category property highlighted that is throwing the error:
Any help trying to work out why there is an error being thrown on desearlizing the list from JSON to C# will be much appreciated.
I'm not sure what your raw JSON looks like, but I'd try one of two things:
Use the [JsonArray]attribute (docs) on your ImageSet property.
[JsonArray]
public List<ImageSet> ImageSet { get; set; }
Consider a different name for your ImageSet property, or the name that it is being serialized to. You've doubled up on the ImageSet name, using it represent the name of the class as well as the property that holds a list of that class.
Best of luck.