0

我有一个 JSON 字符串(根据验证器)是有效的 JSON,我一直试图将其解析为 c# 中的对象。

示例字符串:

{"asks":[["49999.99000","20.00000000"],["900.00000","4.00000000"],["100.00000","5.00000000"]],"bids":[["5.40000","15.06500000"],["5.53675","0.50000000"],["5.00000","6.00000000"]]}

我曾尝试使用http://json2csharp.com/它建议这个类(它确实有效):

public class RootObject
{
    public List<List<string>> asks { get; set; }
    public List<List<string>> bids { get; set; }
}

但是我想像List<Ask> asks { get; set; }. 我尝试了以下方法:

public class Orderbook
{
    public List<Ask> asks { get; set; }
    public List<Bid> bids { get; set; }
}

public class Ask
{
    public double amount { get; set; }
    public double price { get; set; }
}

public class Bid
{
    public double amount { get; set; }
    public double price { get; set; }
}

但这会失败,因为类型'namespace.Ask'不支持数组的反序列化。

4

1 回答 1

1

不需要AskBid

var orderBook = JsonConvert.DeserializeObject<Orderbook>(json); //Json.Net
//OR
var orderBook = new JavaScriptSerializer().Deserialize<Orderbook>(json);  //JavaScriptSerializer

public class Orderbook
{
    public List<List<string>> asks { get; set; }
    public List<List<string>> bids { get; set; }
}

顺便说一句:值是字符串("49999.99000")不是双精度

编辑

asks并且bids数组数组,因此将它们转换为具体类的数组(在反序列化期间)需要很多技巧(如果可能的话)。你为什么不简单地迭代orderBook以形成你想要的?

var asks = orderBook.asks.Select(a => 
                      new Ask { 
                          amount = double.Parse(a[0],CultureInfo.InvariantCulture), 
                          price = double.Parse(a[1],CultureInfo.InvariantCulture)
                      }).ToList();
于 2013-03-31T20:29:43.983 回答