【问题标题】:Deserialize JSON to List将 JSON 反序列化为列表
【发布时间】:2020-02-26 17:57:39
【问题描述】:

我有这个 Json:

{
  "trades": [
    {
      "id": "4004",
      "instrument": "EUR_USD",
      "price": "1.08938",
      "openTime": "2020-02-26T12:15:32.309973340Z",
      "initialUnits": "1",
      "initialMarginRequired": "0.0363",
      "state": "OPEN",
      "currentUnits": "1",
      "realizedPL": "0.0000",
      "financing": "0.0000",
      "dividendAdjustment": "0.0000",
      "unrealizedPL": "-0.0026",
      "marginUsed": "0.0362",
      "takeProfitOrder": {
        "id": "4005",
        "createTime": "2020-02-26T12:15:32.309973340Z",
        "type": "TAKE_PROFIT",
        "tradeID": "4004",
        "price": "1.09099",
        "timeInForce": "GTC",
        "triggerCondition": "DEFAULT",
        "state": "PENDING"
      }
    }
  ],
  "lastTransactionID": "4010"
}

和类:

public class TakeProfitOrder
{
    public string id { get; set; }
    public string createTime { get; set; }
    public string type { get; set; }
    public string tradeID { get; set; }
    public string price { get; set; }
    public string timeInForce { get; set; }
    public string triggerCondition { get; set; }
    public string state { get; set; }
}

public class Trade
{
    public string id { get; set; }
    public string instrument { get; set; }
    public string price { get; set; }
    public string openTime { get; set; }
    public string initialUnits { get; set; }
    public string initialMarginRequired { get; set; }
    public string state { get; set; }
    public string currentUnits { get; set; }
    public string realizedPL { get; set; }
    public string financing { get; set; }
    public string dividendAdjustment { get; set; }
    public string unrealizedPL { get; set; }
    public string marginUsed { get; set; }
    public TakeProfitOrder takeProfitOrder { get; set; }
}

public class RootObject
{
    public List<Trade> trades { get; set; }
    public string lastTransactionID { get; set; }
}

我反序列化:

var result = JsonConvert.DeserializeObject<RootObject>(Json);
var price = result.trades.Select(p => p.price).ToList();
price.ForEach(Console.WriteLine);

它有效。我可以在“交易”中访问“价格”,但我不知道如何访问“获利订单”中的“价格”。我需要将“takeProfitOrder”中的“price”值放入列表中。我确信这是非常简单的事情,但我无法弄清楚如何去做,即使在查看了一些类似的例子之后。

有人可以帮帮我吗?

【问题讨论】:

    标签: c# json list object json-deserialization


    【解决方案1】:

    很简单

    result.trades.Select(p => p.takeProfitOrder.price)
    

    你应该从这个例子中更好地理解

    foreach (Trade trade in result.trades)
    {
        TakeProfitOrder takeProfitOrder = trade.takeProfitOrder;
        Console.WriteLine(takeProfitOrder.price);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 2016-05-30
      • 2012-03-07
      • 2023-03-13
      • 1970-01-01
      相关资源
      最近更新 更多