C# Deserialize JSON to List [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 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);

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

deserialize json into my C# object gives error

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

.net core API sending array object

I have student class with array StudentPhones. When i remove StudentPhones property from Student class is working perfectly when post with Postman. But when add StudentPhones property then Postman gives me this error:
{
"StudentPhones": [
"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'DataAccess.StudentPhone' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\nTo 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.\r\nPath 'StudentPhones', line 4, position 23."
]
}
public class Student
{
public string StudentName { get; set; }
public string StudentSurname { get; set; }
public StudentPhone StudentPhones { get; set; }
}
public class StudentPhone
{
public int PhoneType{ get; set; }
public string PhoneNumber { get; set; }
}
public async Task<ServiceResult> SaveStudent([FromBody]Student student)
{
}
How can I post this json? (I am using angular 6 in real, postman is only for example.)
my json
{
"studentName": "test",
"studentSurname": "test",
"studentPhones": [
{
"phoneType": 1,
"phoneNumber ": "111111111"
},
{
"phoneType": 2,
"phoneNumber ": "2222222222"
}
],
}
You have an array of phones in your JSON, so instead of public StudentPhone StudentPhones { get; set; } in your model, you should have public List<StudentPhone> StudentPhones { get; set; }

define string structure for deserialize json object nested

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.

Categories

Resources