1

我有个问题。我编写了 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
            }
        }
    ]
}
4

1 回答 1

2

您的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);
于 2020-10-22T17:54:05.530 回答