小编典典

Json对象针对给定的键返回null

json

我正在尝试从字符串(从Web获取)中读取JSON,但返回null

具体来说,result.append(name + id);给我nullnull

JSONParser parser = new JSONParser();
try {
    Object obj = parser.parse(datJ);
    JSONObject jsonObject = (JSONObject) obj;
    String name = (String) jsonObject.get("name");
    Integer id = (Integer) jsonObject.get("id");
    result.append(name + id);

} catch (MalformedURLException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
} catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
} catch (org.json.simple.parser.ParseException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

考虑datJ包含以下JSON字符串:

{
    "rikeard":{
        "id":2828822,
        "name":"Rikeard",
        "profileIconId":688,
        "summonerLevel":30,
        "revisionDate":1422917445000
    }
}

编辑:最终代码工作

JSONParser parser = new JSONParser();
        try {
            String datJ = IOUtils.toString(new URL(url));
             Object obj = parser.parse(datJ);
                JSONObject rikeardObject = (JSONObject) ((Map<?, ?>) obj).get("rikeard");
                String name = (String) rikeardObject.get("name");
                Long id = (Long) rikeardObject.get("id");

特别感谢Sufian和Ved!


阅读 269

收藏
2020-07-27

共1个答案

小编典典

“ id”和“ name”位于JSON对象内部,键为“ rikeard”。因此,您需要进行如下更改:

JSONParser parser = new JSONParser();
try {
    Object obj = parser.parse(datJ);
    JSONObject jsonObject = (JSONObject) obj;
    JSONObject rikeardObject = (JSONObject) obj.get("rikeard");
    String name = (String) rikeardObject.get("name");
    Integer id = (Integer) rikeardObject.get("id");
    result.append(name + id);

} catch (MalformedURLException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
} catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
} catch (org.json.simple.parser.ParseException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}
2020-07-27