JSON.Net - cannot deserialize the current json object (for example, {"name": "value"}) in type 'system.collections.generic.list`1

I have 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 this is a kind of list of matches. And I have a class to deserialize it:

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 as follows:

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

But I get an exception:

It is not possible to deserialize the current JSON object (for example, {"name": "value"}) to type 'System.Collections.Generic.List`1 [ClassNameHere]' because the type requires a JSON array (for example, [1,2,3 ]) for deserialization correctly.

If I change the code as follows:

var mList= JsonConvert.DeserializeObject(jsonstr);

Then it is serialized, but not as a list, as an object. How can i fix this?

+4
2

Deserializer IDictionary<string, Match>

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

"40" , Match

, :

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

KeyValuePair:

key - "40"
value - Match { Name = "Team",  ... }
+6
"50": {
         "name": "Team A vs Team D",
         "value": {
                    "home": 0,
                    "away": 2
                  }
      }

Desirializer . json- value . :

"50": {
         "name": "Team A vs Team D",
         "value": [{
                     "home": 0,
                     "away": 2
                  }]
      }

json- value . [ ]

+4

Source: https://habr.com/ru/post/1568950/


All Articles