我有一个json字符串:
{"GetOrderListResponse":
{"orderListResponse":
{
"orderDetails":
[
{"order":
{
"orderId":208,
"legDetails":
{
"legNumber":1,
"symbolInfo":
{
"symbol":"CSCO"
}
}
}
},
{"order":
{
"orderId":200,
"legDetails":
[
{
"legNumber":1,
"symbolInfo":
{
"symbol":"IBM"
}
},
{
"legNumber":2,
"symbolInfo":
{
"symbol":"IBM",
"callPut":"CALL",
"expYear":2010,
"expMonth":4,
"expDay":17,
"strikePrice":115
}
}
]
}
}
]
}
}
}
我有对象
public class OrderListResponse
{
public List<OrderDetail> orderDetails { get; set; }
}
public class OrderDetail
{
public Order order { get; set; }
}
public class Order
{
public long orderId { get; set; }
public List<LegDetail> legDetails { get; set; }
}
public class LegDetail
{
public long legNumber { get; set; }
public Symbol symbolInfo { get; set; }
}
public class Symbol
{
public string symbol { get; set; }
public string callPut { get; set; }
public int expYear { get; set; }
public int expMonth { get; set; }
public int expDay { get; set; }
public int strikePrice { get; set; }
}
所以当我使用代码时:
var objectValue = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, object>>>(jsonString);
var objectDeserialize = JsonConvert.DeserializeObject<OrderListResponse>(objectValue.Values.First()["orderListResponse"].ToString());
我收到错误消息:
无法将当前JSON对象(例如{&#34; name&#34;:&#34; value&#34;})反序列化为类型System.Collections.Generic.List`1 [LegDetail]& #39;因为该类型需要JSON数组(例如[1,2,3])才能正确反序列化。
有人能告诉我正确的代码吗?
答案 0 :(得分:1)
第一顺序的logdetails不是数组......
"legDetails":
{
"legNumber":1,
"symbolInfo":
{
"symbol":"CSCO"
}
}
应该如下:
"legDetails":
[{
"legNumber":1,
"symbolInfo":
{
"symbol":"CSCO"
}
}]
<强>更新强>
所以现在问题是你想要反序列化一个有时可能是数组的json,有时可能代表一个对象。
查看另一个stackoverflow线程:Deserializing JSON when sometimes array and sometimes object
这可能有助于您解决问题。
答案 1 :(得分:0)
您的JSON无效。它应该是:
{
"GetOrderListResponse":{
"orderListResponse":{
"orderDetails":[
{
"order":{
"orderId":208,
"legDetails":[
{
"legNumber":1,
"symbolInfo":{
"symbol":"CSCO"
}
}
]
}
},
{
"order":{
"orderId":200,
"legDetails":[
{
"legNumber":1,
"symbolInfo":{
"symbol":"IBM"
}
},
{
"legNumber":2,
"symbolInfo":{
"symbol":"IBM",
"callPut":"CALL",
"expYear":2010,
"expMonth":4,
"expDay":17,
"strikePrice":115
}
}
]
}
}
]
}
}
}