使用JSON.NET反序列化具有奇数结构的JSON

本文关键字:JSON 结构 NET 反序列化 使用 | 更新日期: 2023-09-27 18:27:50

我正在尝试使用JSON.NET的JsonConvert类将一些JSON反序列化为对象。

我在JSON结构示例中使用的代码:

var desObj = JsonConvert.DeserializeObject<Market>("{'"success'":'"1'",'"return'":
{'"sellorders'":
[{'"sellprice'":'"0.00001099'",'"quantity'":'"60.00000000'",'"total'":'"0.00065940'"},
{'"sellprice'":'"0.00001100'",'"quantity'":'"1000.00000000'",'"total'":'"0.01100000'"},
{'"sellprice'":'"0.00001105'",'"quantity'":'"60.00000000'",'"total'":'"0.01200'"}]}}");

我的市场类别:

class Market
    {
        [JsonProperty("success")]
        public int Success { get; set; }
        [JsonProperty("sellorders")]
        public List<SellOrder> SellOrders {get; set;}
        [JsonProperty("buyorders")]
        public List<BuyOrder> BuyOrders {get; set;}
    }
    public class SellOrder
    {
        [JsonProperty("sellprice")]
        public decimal SellPrice { get; set; }
        [JsonProperty("quantity")]
        public decimal Quantity { get; set; }
        [JsonProperty("total")]
        public decimal Total { get; set; }
    }
    public class BuyOrder
    {
        [JsonProperty("buyprice")]
        public decimal BuyPrice { get; set; }
        [JsonProperty("quantity")]
        public decimal Quantity { get; set; }
        [JsonProperty("total")]
        public decimal Total { get; set; }
    }

给我带来问题的是数据在"return"键下。如果我取下回车键,这将非常有效。我该如何让我的市场对象表现成这样:

foreach(SellOrder sellorder in desObj.SellOrders)
{
    Console.WriteLine(sellorder.total.ToString());
}

我尝试过将return属性作为一个动态列表,然后以这种方式检索买卖订单,但似乎什么都不起作用。有什么想法吗?

使用JSON.NET反序列化具有奇数结构的JSON

你不能做这样的事情吗?

class Market
    {
      [JsonProperty("success")]
      public int Success { get; set; }
      [JsonProperty("return")]
      public Container Container { get; set; }
    }
    class Container
    {
      [JsonProperty("sellorders")]
      public List<SellOrder> SellOrders { get; set; }
      [JsonProperty("buyorders")]
      public List<BuyOrder> BuyOrders { get; set; }
    }
    public class SellOrder
    {
      [JsonProperty("sellprice")]
      public decimal SellPrice { get; set; }
      [JsonProperty("quantity")]
      public decimal Quantity { get; set; }
      [JsonProperty("total")]
      public decimal Total { get; set; }
    }
    public class BuyOrder
    {
      [JsonProperty("buyprice")]
      public decimal BuyPrice { get; set; }
      [JsonProperty("quantity")]
      public decimal Quantity { get; set; }
      [JsonProperty("total")]
      public decimal Total { get; set; }
}

然后访问这样的数据:

foreach(SellOrder sellorder in desObj.Container.SellOrders)
{
    Console.WriteLine(sellorder.total.ToString());
}