C# 无法将当前JSON数组反序列化为类型
我正在尝试反序列化以下JSON数据:C# 无法将当前JSON数组反序列化为类型,c#,json,json.net,deserialization,C#,Json,Json.net,Deserialization,我正在尝试反序列化以下JSON数据: { "bids": [ [ "392031.00000000", "0.00254444" ], [ "390000.00000000", "0.52917503" ], ...... ], "asks": [ [ "392999.00000000", "1.00000000" ], [ "
{
"bids": [
[
"392031.00000000",
"0.00254444"
],
[
"390000.00000000",
"0.52917503"
],
......
],
"asks": [
[
"392999.00000000",
"1.00000000"
],
[
"393000.00000000",
"0.31572236"
],
.....
]
}
我已经研究过类似的问题,比如,但我没有得到接近的结果,并且注意到在这个问题中,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; }
}
公共类OrderBookElement
{
//我还尝试了下面的注释代码
//[JsonProperty(PropertyName=“0”)]
//公共双价{get;set;}
//[JsonProperty(PropertyName=“1”)]
//公共双卷{get;set;}
列表值;
}
公共类OrderBookResponse
{
[JsonProperty(PropertyName=“bids”)]
列出出价{get;set;}
[JsonProperty(PropertyName=“asks”)]
列表请求{get;set;}
}
下面是我用于反序列化的代码
var ordBook = JsonConvert.DeserializeObject<OrderBookResponse>(jsonResponse);
var ordBook=JsonConvert.DeserializeObject(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.
无法将当前JSON数组(例如[1,2,3])反序列化为“RestAPI.OrderBookElement”类型,因为该类型需要一个JSON对象(例如{“name”:“value”})才能正确反序列化。
要修复此错误,请将JSON更改为JSON对象(例如{“name”:“value”}),或将反序列化类型更改为数组或实现可从JSON数组反序列化的集合接口(例如ICollection、IList)类似列表的类型。还可以将JsonArrayAttribute添加到类型中,以强制它从JSON数组反序列化。
您展示的JSON将由以下内容表示:
public class OrderBookResponse
{
[JsonProperty("bids")]
public List<List<string>> Bids { get; set; }
[JsonProperty("asks")]
public List<List<string>> Asks { get; set; }
}
公共类OrderBookResponse
{
[JsonProperty(“投标”)]
公共列表出价{get;set;}
[JsonProperty(“asks”)]
公共列表要求{get;set;}
}
JSON中的bids
和asks
属性都只是字符串数组
我建议反序列化为与JSON匹配的模型,然后分别将其转换为更有用的模型。也许可以对类应用属性来说服Json.NET做您想做的事情,但我倾向于认为,当出现重大差异时(不仅仅是属性名称),将两个模型分开是值得的,一个用于序列化,另一个用于代码的其余部分。我有类似的错误,现在我正在寻找最佳解决方案,现在我可以向您提供以下内容:var ordBook=JsonConvert.DeserializeObject(jsonResponse);TO:var ordBook=JsonConvert.DeserializeObject(jsonResponse);看起来像是
出价
和询问
的列表,因为您有[[1,2,3],…],…],…]