我正在尝试反序列化以下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.
答案 0 :(得分:6)
您展示的JSON将代表:
public class OrderBookResponse
{
[JsonProperty("bids")]
public List<List<string>> Bids { get; set; }
[JsonProperty("asks")]
public List<List<string>> Asks { get; set; }
}
JSON中的bids
和asks
属性都只是字符串数组的数组。
我建议反序列化到与JSON匹配的模型,然后将其转换为更有用的模型。 可能可以将属性应用到您的类中以说服Json.NET做您想做的事情,但我倾向于认为当时存在重大差异(而不仅仅是属性名称) ),值得将两个模型分开,一个用于序列化,另一个用于代码的其余部分。