Json对象针对给定的键返回null [英] Json object returning null against given key

查看:112
本文介绍了Json对象针对给定的键返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to read JSON from string (obtained from web), but it returns 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字符串:

Consider that datJ contains following JSON string:

{
    "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!

推荐答案

"id"和"name"位于JSON对象中,键为"rikeard".因此,您需要进行如下更改:

"id" and "name" are inside the JSON object against the key "rikeard". So you need to make changes like following:

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

这篇关于Json对象针对给定的键返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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