null指针异常java使用maven组org.json访问嵌套的json对象

时间:2016-10-29 07:09:30

标签: java json maven jsonobject

这是我的依赖

 <dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
  <version>20160810</version>
</dependency>

这是我的json对象

{
   "authorize": {
       "balance": "9984.06",
       "country": "id",
       "currency": "USD",
       "email": "xxxx.xxxx@gmail.com",
       "fullname": "  ",
       "is_virtual": 1,
       "landing_company_fullname": "Binary Ltd",
       "landing_company_name": "virtual",
       "loginid": "VRg4423",
       "scopes": [
         "read",
         "trade"
       ]
   }
}

这是我的代码

JSONObject jsonObject = new JSONObject(fil);
JSONObject jsonChildObject = (JSONObject) jsonObject.get("authorize");
Iterator iterator  = jsonChildObject.keys();
String key = null;
while (iterator.hasNext()) {
    key = (String) iterator.next();
    System.out.println("balance value:" + ((JSONObject) jsonChildObject.get(key)).get("balance"));
}

我不知道为什么我无法访问所有子节点值。它返回空指针异常,没有&#34;授权&#34;我无法获得父母价值。

1 个答案:

答案 0 :(得分:0)

让我们看看你的代码,我们会发现问题:

JSONObject jsonObject = new JSONObject(fil);
 // jsonObject is now your whole json
 // {
 //    "authorize": 
 //     ...
 // }

JSONObject jsonChildObject = (JSONObject) jsonObject.get("authorize");
 // the "authorize" child node is now contained in jsonChildObject
 // {
 //    "balance": "9984.06",
 //    "country": "id",
 //    "currency": "USD",
 //     ...
 // }

Iterator iterator  = jsonChildObject.keys();
// jsonChildObject.keys() iterates over this set:
// ["balance", "country", "currency" ... ]

String key = null;
while (iterator.hasNext()) {
    key = (String) iterator.next(); 
    // the very first iteration, key will have the value "balance"

    System.out.println("balance value:" 
       + ((JSONObject) jsonChildObject.get(key)).get("balance"));
    // and here you try to get the element "balance" from the element with the key "balance"
}

基本上就行了

((JSONObject) jsonChildObject.get(key)).get("balance"))

在第一次迭代中看起来像这样:

((JSONObject) jsonChildObject.get("balance")).get("balance"))

当然不存在。

1)如果您只想要“余额”,请不要遍历密钥并删除while循环。只需写下jsonChildObject.get("balance")

即可

2)如果你需要所有孩子并且你想要保持while循环,你可以切换他们的键:< / p>

  while (iterator.hasNext()) {
    key = (String) iterator.next();
    switch(key){
        case "balance": 
             float balance = jsonChildObject.get(key);
             break;
        case "country":
            ...
    }

它或者是其他一些库(如Gson)自动将你的json映射到你之前编写的简单POJO中

Gson的Maven依赖

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.2.2</version>
    </dependency>

但我会选择 1),只需通过手动调用jsonChildObject.get("balance")...get("country");来获取所有值,依此类推。

修改

我刚刚意识到你在获得“授权”时遇到了问题,也许一个简单的print会告诉你你的json是怎样的:

System.out.println(jsonObject.toString(3));  // should give you a nicely printed JSON. If this is already `null` then the problem is already in `fil` which might be the wrong json.