[英]JSON.Net - cannot deserialize the current json object (e.g. {“name”:“value”}) into type 'system.collections.generic.list`1
I have a JSON like 我有一个类似的JSON
{
"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: 我试图像这样反序列化json:
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. 无法将当前JSON对象(例如{“name”:“value”})反序列化为类型'System.Collections.Generic.List`1 [ClassNameHere]',因为该类型需要JSON数组(例如[1,2,3] )正确反序列化。
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>
在这种情况下,您应该向Deserializer询问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 并且第一个元素将具有键“40” ,并且值将是Match
实例
Other words this part: 换句话说这部分:
"40": {
"name": "Team A vs Team B",
"value": {
"home": 1,
"away": 0
}
will result in KeyValuePair: 将导致KeyValuePair:
key - "40"
value - Match { Name = "Team", ... }
"50": {
"name": "Team A vs Team D",
"value": {
"home": 0,
"away": 2
}
}
The desirializer works correctly. desirializer工作正常。 In this json code value
is an object. 在这个json代码中, value
是一个对象。 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. 在这个json代码中, value
被声明为一个对象数组。 Notice the [
and ]
注意[
和]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.