首页 > 解决方案 > ASP.NET C# JSON 反序列化嵌套数组:无法对空引用执行运行时绑定

问题描述

我在网上找到了一些看起来应该可行的逻辑示例,但我仍然无法解析嵌套的 JSON 数组来访问和处理数组中的每个值。我可以通过执行以下操作成功访问其他 API 调用响应中的子参数:string test = object.parameter1.parameter2.array[0].targetValue(此数组中只有一个值)。但是,我没有得到我认为的相同结果,因为数组中有许多值的语法可能会导致下面列出的错误。

   private static string GetPositions()
    {

        var client = new RestClient("https://api.tdameritrade.com/v1/accounts/" + accountId);
        client.Timeout = -1;
        var request = new RestRequest(Method.GET);
        request.AddHeader("Authorization", "Bearer " + ReadAccessToken());
        IRestResponse response = client.Execute(request);

        dynamic positions = JsonConvert.DeserializeObject<JObject>(response.Content);

        var openPositions = "";


        //Cannot perform runtime binding on a null reference
        //var openPositions = positions.securitiesAccount.positions[0].instrument.symbol;


        //Object reference not set to an instance of an object
        //foreach (var child in positions["securitiesAccount"]["positions"])
        //{
        //    openPositions = child["instrument"]["symbol"].ToString();
        //}

        //Cannot perform runtime binding on a null reference    
        foreach (JObject child in positions["securitiesAccount"]["positions"].OfType<JObject>())
        {
            openPositions = child["instrument"]["symbol"].ToString();
        }

            return openPositions;
    }

我试图循环遍历每个未平仓头寸并存储在数据库中的嵌套 JSON 数组的示例;我唯一遇到的问题是访问 position[] 中的每个位置 -

{
  "securitiesAccount": {
    "type": "type",
    "accountId": "id",
    "roundTrips": 0,
    "isDayTrader": false,
    "isClosingOnlyRestricted": false,
    "positions": [
      {
        "shortQuantity": 0,
        "averagePrice": 73.495,
        "currentDayProfitLoss": 7.56,
        "currentDayProfitLossPercentage": 0.76,
        "longQuantity": 14,
        "settledLongQuantity": 14,
        "settledShortQuantity": 0,
        "instrument": {
          "assetType": "EQUITY",
          "cusip": "1",
          "symbol": "symbol1"
        },
        "marketValue": 1001,
        "maintenanceRequirement": 300.3
      },
      {
        "shortQuantity": 0,
        "averagePrice": 17.659846153846,
        "currentDayProfitLoss": 12.33,
        "currentDayProfitLossPercentage": 1.12,
        "longQuantity": 65,
        "settledLongQuantity": 0,
        "settledShortQuantity": 0,
        "instrument": {
          "assetType": "EQUITY",
          "cusip": "2",
          "symbol": "symbol2"
        },
        "marketValue": 1115.4,
        "maintenanceRequirement": 557.7
      }
    ]
  }
}

任何关于如何实现这一点的建议将不胜感激。

--更新代码供参考--

   private static string GetPositions()
    {

        var client = new RestClient("https://api.tdameritrade.com/v1/accounts/" + accountId);
        client.Timeout = -1;
        var request = new RestRequest(Method.GET);
        request.AddHeader("Authorization", "Bearer " + ReadAccessToken());
        IRestResponse response = client.Execute(request);

        dynamic streamer = JsonConvert.DeserializeObject<JObject>(response.Content);

        var json = streamer.ToString();

        dynamic positions = JsonConvert.DeserializeObject<OpenPositions>(json);

        var openPositions = positions.SecuritiesAccount.Positions[0].Instrument.Symbol.ToString();


        /*
        var test = "";
        OpenPositions securitiesAccount = new OpenPositions();
        SecuritiesAccount positions = new SecuritiesAccount();
        Position instrument = new Position();
        Instrument symbol = new Instrument();
        
        foreach (var child in json[securitiesAccount][positions])
        {
            test = child[instrument][symbol].ToString();
        }
        */

        //return test;


        return openPositions;
    }

以下是将 JSON 参数转换为 C 对象的类:

public partial class OpenPositions
{
    [JsonProperty("securitiesAccount")]
    public SecuritiesAccount SecuritiesAccount { get; set; }
}

public partial class SecuritiesAccount
{
    [JsonProperty("type")]
    public string Type { get; set; }

    [JsonProperty("accountId")]
    [JsonConverter(typeof(ParseStringConverter))]
    public long AccountId { get; set; }

    [JsonProperty("positions")]
    public Position[] Positions { get; set; }

}


public partial class Position
{

    [JsonProperty("instrument")]
    public Instrument Instrument { get; set; }

}

public partial class Instrument
{
    [JsonProperty("assetType")]
    public AssetType AssetType { get; set; }

    [JsonProperty("cusip")]
    public string Cusip { get; set; }

    [JsonProperty("symbol")]
    public string Symbol { get; set; }
}

var openPositions = position.SecuritiesAccount.Positions[0].Instrument.Symbol.ToString(); 是在空引用异常上引发无法执行运行时绑定的代码。但是,这行代码只是为了测试我是否可以获取嵌套字符串,最终目标是遍历每个 Position[] 并返回可能存在的每个未结订单。

“/”应用程序中的服务器错误

标签: c#json

解决方案


推荐阅读