Failure to serialize json by JsonConvert library [duplicate] - c#

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

Related

Deserialize object error error when reading a list

I have the next response from an API
{
"ArticleSpecification": [
{
"Name": "SomeName",
"Description ": "Description ",
"Label": "SomeLabel",
}
]
}
Then I try to Deserialize the object using my class
public class ArticleSpecification
{
[JsonProperty("Description")]
public string Description { get; set; }
[JsonProperty("Label")]
public string Label { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
}
The deserialize section looks like this
if (responseMessage.IsSuccessStatusCode)
{
var json = responseMessage.Content.ReadAsStringAsync().Result;
List<ArticleSpecification> articles = JsonConvert.DeserializeObject<List<ArticleSpecification>(json);
}
The result is the next :
Unhandled exception. Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Program+ArticleSpecification]' 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
The response from API is an object, not the array.
Your response actually is an object, which has the property: ArticleSpecification which is the array. Example of class for such reponse:
class APIResponse {
public ArticleSpecification[] ArticleSpecification { get; set; }
}
Then you can deserialize response:
var response = JsonConvert.DeserializeObject<APIResponse>(json);
List<ArticleSpecification> articles = new List<ArticleSpecification>(response.ArticleSpecification);
Something among those lines.

How to remove double quotes from a string inside JSON string?

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

Deserializing a object containg dictionary objects using JsonConvert C#

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

C# Deserialize JSON to List [duplicate]

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 5 years ago.
I have come across a problem I don't understand when trying to deserialize a JSON string (containing multiple objects) into a List. Here is the JSON.
[
{
"id":2,
"name":"Race 1",
"raceDateTime":"2017-09-02T14:27:39.654",
"raceStartTime":"2017-09-02T14:27:39.654",
"description":"string",
"maxEntries":0,
"currentEntries":0,
"status":0
},
{
"id":3,
"name":"Race 2",
"raceDateTime":"2017-09-02T14:27:39.654",
"raceStartTime":"2017-09-02T14:27:39.654",
"description":"string",
"maxEntries":0,
"currentEntries":0,
"status":0
},
{
"id":4,
"name":"Race 3",
"raceDateTime":"2017-09-02T14:27:39.654",
"raceStartTime":"2017-09-02T14:27:39.654",
"description":"string",
"maxEntries":0,
"currentEntries":0,
"status":0
},
{
"id":5,
"name":"Race 4",
"raceDateTime":"2017-09-02T14:27:39.654",
"raceStartTime":"2017-09-02T14:27:39.654",
"description":"string",
"maxEntries":0,
"currentEntries":0,
"status":0
}
]
I then have the JSON parameters matching my Model.
public class RaceModel
{
public int id { get; set; }
public string name { get; set; }
public DateTime raceDateTime { get; set; }
public DateTime raceStartTime { get; set; }
public string description { get; set; }
public int maxEntries { get; set; }
public int currentEntries { get; set; }
public int status { get; set; }
}
public class RaceList
{
public List<RaceList> racelist { get; set; }
}
And my code to get the JSON from the REST API request is below:
string APIServer = Application.Current.Properties["APIServer"].ToString();
string Token = Application.Current.Properties["Token"].ToString();
var client = new RestClient(APIServer);
var request = new RestRequest("api/race", Method.GET);
request.AddHeader("Content-type", "application/json");
request.AddHeader("Authorization", "Bearer " + Token);
var response = client.Execute(request) as RestResponse;
var raceobject = JsonConvert.DeserializeObject<RaceList>(response.Content);
But I get this error (Using Newtonsoft.JSON)
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'TechsportiseApp.API.Models.RaceList' 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.
I'd like to have a list/collection of objects I can then iterate through and work with.
Can anyone advise what I've done wrong?
Your response is a array of objects and you are specifing a single object in the T parameter. Use List<RaceModel> instead of RaceList:
var raceobject = JsonConvert.DeserializeObject<List<RaceModel>>(response.Content);

Cannot deserialize the current JSON object to generic List type

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.

Categories

Resources