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);
Related
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 :)
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 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.
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.
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);
}