Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

java - Json object returning null against given key

I'm trying to read JSON from string (obtained from web), but it returns null.

Specifically, result.append(name + id); gives me 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();
}  

Consider that datJ contains following JSON string:

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

EDIT: Final code working

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

Special Thanks for Sufian and Ved!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use this method it's work for me,

    private void extractJson(){
    String jsonString="{"rikeard":{"id":2828822,"name":"Rikeard","profileIconId":688,"summonerLevel":30,"revisionDate":1422917445000}}";

    try {
        JSONObject jsonObject=new JSONObject(jsonString);
        if(jsonObject!=null){
            jsonObject=jsonObject.optJSONObject("rikeard");
            if(jsonObject!=null){
                String id=jsonObject.optString("id");
                Log.d("MainActivity","id="+id);
            }
        }


    } catch (JSONException e) {
        e.printStackTrace();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...