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?
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", ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With