无法反序列化JSON

时间:2013-03-31 20:20:37

标签: c# json

我有一个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; }
}

但是 Type'namespace.Ask'不支持反序列化数组。

1 个答案:

答案 0 :(得分: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; }
}

BTW:值是字符串("49999.99000")而不是双倍

修改

asksbids数组数组,因此将它们转换为一个concerete类数组(在反序列化期间)需要很多技巧(如果可能的话)。你为什么不简单地迭代orderBook来形成你想要的东西?

var asks = orderBook.asks.Select(a => 
                      new Ask { 
                          amount = double.Parse(a[0],CultureInfo.InvariantCulture), 
                          price = double.Parse(a[1],CultureInfo.InvariantCulture)
                      }).ToList();