JSON.Net-无法将当前json对象(例如{"name":"value"})反序列化为类型'system.collections.generic.list`1 [英] JSON.Net - cannot deserialize the current json object (e.g. {"name":"value"}) into type 'system.collections.generic.list`1

查看:555
本文介绍了JSON.Net-无法将当前json对象(例如{"name":"value"})反序列化为类型'system.collections.generic.list`1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似JSON的

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; }
}

我正在尝试像这样反序列化json:

I am trying to deserialize json like this:

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

但是我遇到了异常:

无法反序列化当前JSON对象(例如{"name":"value"}) 变成类型'System.Collections.Generic.List`1 [ClassNameHere]',因为 该类型需要JSON数组(例如[1,2,3])进行反序列化 正确.

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.

如果我将代码更改为:

var mList= JsonConvert.DeserializeObject(jsonstr);

然后将其序列化,但不作为对象序列化.我怎样才能解决这个问题?

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

推荐答案

在这种情况下,您应该向Deserializer请求 IDictionary<string, Match>

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

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

第一个元素将具有键"40" ,其值将为Match实例

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

换句话说,这部分:

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

将产生KeyValuePair:

will result in KeyValuePair:

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

这篇关于JSON.Net-无法将当前json对象(例如{"name":"value"})反序列化为类型'system.collections.generic.list`1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆