I am getting the following error while deserializing. My coding blocks which I have been trying to deserialize are given below.
Error: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Subject' 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. Path 'Students[3].Subject'.....
JSON:
{
"Students":[
{
"Name":"Mr. X",
"Class":"Ten",
"Roll":5,
"Subject":{
"Name":"Math",
"Marks":90
}
},
{
"Name":"Mr. Y",
"Class":"Ten",
"Roll":7,
"Subject":{
"Name":"Math",
"Marks":80
}
},
{
"Name":"Mr. Z",
"Class":"Ten",
"Roll":8,
"Subject":{
"Name":"Math",
"Marks":75
}
},
{
"Name":"Mr. A",
"Class":"Ten",
"Roll":1,
"Subject":[
{
"Name":"Math",
"Marks":95
},
{
"Name":"English",
"Marks":75
}
]
}
]
}
Program.cs:
Student_Collection students = new Student_Collection();
.....
string jsonString = await response.Content.ReadAsStringAsync();
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
// this the line where I am getting the error
students = JsonConvert.DeserializeObject<Student_Collection>(jsonString, settings);
Subject.cs:
class Subject
{
public string Name { get; set; }
public int Marks { get; set; }
}
Student.cs
class Student
{
public string Name { get; set; }
public string Class { get; set; }
public int Roll { get; set; }
public Subject Subject { get; set; }
}
Student_Collection.cs
class Student_Collection
{
public List<Student> students { get; set; }
}