JSON.Net - cannot deserialize the current json object (e.g. {"name":"value"}) into type 'system.collections.generic.list`1

Sefa picture Sefa · Dec 25, 2014 · Viewed 24.2k times · Source

I have a JSON like

{
  "40": {
    "name": "Team A vs Team B",
    "value": {
      "home": 1,
      "away": 0
    }
  },
  "45": {
    "name": "Team A vs Team C",
    "value": {
      "home": 2,
      "away": 0
    }
  },
  "50": {
    "name": "Team A vs Team D",
    "value": {
      "home": 0,
      "away": 2
    }
  }
}

So it's kind of list of matches. And I have the class to deserialize it into:

public class Match
{
    [JsonProperty(PropertyName = "name")]
    public string Name { get; set; }
    [JsonProperty(PropertyName = "value")]
    public Value Values { get; set; }
}

public class Value
{
    [JsonProperty(PropertyName = "home")]
    public int Home { get; set; }
    [JsonProperty(PropertyName = "away")]
    public int Away { get; set; }
}

I am trying to deserialize json like this:

var mList= JsonConvert.DeserializeObject<List<Match>>(jsonstr);

But i am getting exception:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ClassNameHere]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

If i change the code like:

var mList= JsonConvert.DeserializeObject(jsonstr);

Then it serializes but not as a list, as a object. How can I fix this?

Answer

Radim K&#246;hler picture Radim Köhler · Dec 25, 2014

In this case, you should ask Deserializer for IDictionary<string, Match>

var mList= JsonConvert.DeserializeObject<IDictionary<string, Match>>(jsonstr);

And the first element would have key "40" and the value will be the Match instance

Other words this part:

"40": {
    "name": "Team A vs Team B",
    "value": {
      "home": 1,
      "away": 0
    }

will result in KeyValuePair:

key - "40"
value - Match { Name = "Team",  ... }