I want to deserialize my json object to my student class
var result = JsonConvert.DeserializeObject<Student>(data);
My json data
{
"student":{
"fname":"997544",
"lname":"997544",
"subject":"IT",
"grade":"F"
}
}
My student class
[Serializable]
public class Student
{
[JsonProperty("fname")]
public string FirstName{ get; set; }
[JsonProperty("lname")]
public string LastName{ get; set; }
[JsonProperty("subject")]
public string Subject { get; set; }
[JsonProperty("grade")]
public string Grade { get; set; }
}
The code does not work, the error says:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Your JSON string currently represents an object with an inner object property named Student. If you want to deserialize to your Student object your JSON string should look like this:
{
"fname":"997544",
"lname":"997544",
"subject":"IT",
"grade":"F"
}
If it's not easy to change your JSON you could also use JObject to help you like so:
var jobject = JObject.Parse(jsonData);
var student = JsonConvert.DeserializeObject<Student>(jobject["student"].ToString());
Or as others have pointed out you can simply create another class wrapper and deserialize directly to that.
if you have to use your downloaded json then you need to create another model class for it
[Serializable]
public class Student
{
[JsonProperty("fname")]
public string FirstName{ get; set; }
[JsonProperty("lname")]
public string LastName{ get; set; }
[JsonProperty("subject")]
public string Subject { get; set; }
[JsonProperty("grade")]
public string Grade { get; set; }
}
[Serializable]
public class NewModel
{
public Student Student { get; set; }
}
then deserialize
var result = JsonConvert.DeserializeObject<NewModel>(data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With