Jmocke Jmocke - 3 months ago 10
C# Question

deserialize json object does not work

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.

Answer

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