1

I have a class like this

public class RootObject
{
    public List<Award> award { get; set; }
}
public class Award
{
    public string name { get; set; }
    public string year { get; set; }
}

Json award

"[{\"name\":\"Student of the month\",\"year\":\"2017-01-01\"},
{\"name\":\"National Hero\",\"year\":\"2017-01-01\"}]"

I deserialize like this

var awardList = JsonConvert.DeserializeObject<RootObject>(award)
foreach (var item in awardList.award)
{
    Profile.Awards.Add(item);
}

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type. What's wrong in this code?

2 Answers 2

1

Based on provided JSON you are deserializing to the wrong type. The provided JSON is just a collection of awards at the root.

Deserialize like...

var awardList = JsonConvert.DeserializeObject<Award[]>(award);
foreach (var item in awardList) {
    Profile.Awards.Add(item);
}

The JSON would have to look like below to match the original code provided

{ 
    "award": [
        {"name":"Student of the month","year":"2017-01-01"},
        {"name":"National Hero","year":"2017-01-01"}
    ]
}
Sign up to request clarification or add additional context in comments.

Comments

0

Json award string that you mentioned is not matching with RootObject class structure.

Serialized String for RootObject should be like this

{"award":[{"name":"Student of the month","year":"2017"},{"name":"National Hero",

"year":"2017"}]}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.