简体   繁体   中英

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

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 (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[ClassNameHere]' because the type requires a JSON array (eg [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?

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",  ... }
"50": {
         "name": "Team A vs Team D",
         "value": {
                    "home": 0,
                    "away": 2
                  }
      }

The desirializer works correctly. In this json code value is an object. Try with this:

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

In this json code value is declared as an array of objects. Notice the [ and ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM