【问题标题】:Cannot deserialze the current JSON array into type无法将当前 JSON 数组反序列化为类型
【发布时间】:2018-01-23 15:19:40
【问题描述】:

我正在尝试反序列化以下 JSON 数据:

{
  "bids": [
    [
      "392031.00000000",
      "0.00254444"
    ],
    [
      "390000.00000000",
      "0.52917503"
    ],
     ......
    ],

   "asks": [
    [
      "392999.00000000",
      "1.00000000"
    ],
    [
      "393000.00000000",
      "0.31572236"
    ],
    .....
    ]
}

我已经研究过类似的问题,例如 this one,但我没有得到接近的结果,并且还注意到在那个问题中 JSON 的结构并不相似。

我的反序列化代码如下

public class OrderBookElement
{
    // I've also tried below commented code
    //[JsonProperty(PropertyName = "0")]
    //public double price { get; set; }

    //[JsonProperty(PropertyName = "1")]
    //public double volume { get; set; }

    List<double> values;
}
public class OrderBookResponse
{
    [JsonProperty(PropertyName = "bids")]
    List<OrderBookElement> bids { get; set; }
    [JsonProperty(PropertyName = "asks")]
    List<OrderBookElement> asks { get; set; }
}

下面是我用于反序列化的代码

var ordBook = JsonConvert.DeserializeObject<OrderBookResponse>(jsonResponse);

这给了我错误:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'RestAPI.OrderBookElement' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. 

【问题讨论】:

  • 我遇到了类似的错误,现在我正在寻找最佳解决方案,现在我可以为您提供 chanhe 这个:var ordBook = JsonConvert.DeserializeObject(jsonResponse); TO:var ordBook = JsonConvert.DeserializeObject>(jsonResponse);
  • 看起来像 bidsasks 的列表列表,因为您有 [ [ 1, 2, 3 ], [ ... ], ... ]

标签: c# json json.net deserialization


【解决方案1】:

您显示的 JSON 将表示为:

public class OrderBookResponse
{
    [JsonProperty("bids")]
    public List<List<string>> Bids { get; set; }

    [JsonProperty("asks")]
    public List<List<string>> Asks { get; set; }
}

JSON 中的 bidsasks 属性都只是一个字符串数组。

我建议反序列化为与 JSON 匹配的模型,然后将其单独转换为更有用的模型。 也许可以将属性应用到你的类以说服 Json.NET 做你想做的事,但我倾向于认为,当出现显着差异时(不仅仅是属性名称),它是值得将这两个模型分开,一个用于序列化,一个用于其余代码。

【讨论】:

    猜你喜欢
    • 2016-04-06
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 2019-03-20
    相关资源
    最近更新 更多