在Java中解析JSON时找不到JSONObject ["sum"] [英] JSONObject["sum"] not found while parsing JSON in Java

查看:135
本文介绍了在Java中解析JSON时找不到JSONObject ["sum"]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题.我编写了JSON解析代码,但它给了我一个错误.我不明白问题是什么.字符串结果是JSON.我需要从sum中输出金额值.返回错误:找不到JSONObject [" sum"]."

I have a problem. I wrote the JSON parsing code, but it gives me an error. I don't understand what the problem is. String result is JSON.I need to output the amount value from sum. Returns an error: "JSONObject["sum"] not found."

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在结构中:

Your sum element is deep below the structure. But your code is expecting it to be under the root object. Your code is assuming the json is in structure:

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

但是您的json数据具有以下结构:

But your json data is in following structure:

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

因此,您需要正确阅读它:

So, you need to read it properly:

        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);

这篇关于在Java中解析JSON时找不到JSONObject ["sum"]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆