簡體   English   中英

在 Java 中解析 JSON 時找不到 JSONObject["sum"]

[英]JSONObject["sum"] not found while parsing JSON in Java

我有個問題。 我寫了 JSON 解析代碼,但它給了我一個錯誤。 我不明白問題是什么。 字符串結果是 JSON。我需要從 sum 中輸出數量值。 返回錯誤:“未找到 JSONObject["sum"]。”

JSONObject json = new JSONObject(result);
JSONObject bpi = json.getJSONObject("sum");
String uuu = bpi.getString ("amount");
System.out.println(uuu);
{
    "data": [
        {
            "txnId": 20071336083,
            "personId": 1,
            "date": "2020-10-21T20:10:56+03:00",
            "errorCode": 0,
            "error": null,
            "status": "SUCCESS",
            "type": "IN",
            "statusText": "Success",
            "trmTxnId": "403300256",
            "account": "xxx",
            "sum": {
                "amount": 10,
                "currency": 643
            }
        }
    ]
}

您的sum元素位於結構下方。 但是您的代碼期望它位於根對象下。 您的代碼假設 json 在結構中:

{
    "sum": {
        "amount": 10,
        "currency": 643    
    }
}

但是您的 json 數據采用以下結構:

{ //ROOT JSONObject
  "data": [ // JSONArray
    { //JSONObject - first element of array index 0
      "account": "xxx",
      "sum": { //JSONObject
        "amount": 10,  //value
        "currency": 643
      }
    }
  ]
}

因此,您需要正確閱讀它:

        JSONObject json = new JSONObject(result);
        JSONArray data = json.getJSONArray("data");
        JSONObject el = (JSONObject) data.get(0);
        JSONObject sum = el.getJSONObject("sum");
        String uuu = sum.getString("amount");
        System.out.println(uuu);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM