Json object returning null against given key

前端 未结 3 2272
盖世英雄少女心
盖世英雄少女心 2020-12-12 03:40

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

Specifically, result.append(name + id); gives me nulln

相关标签:
3条回答
  • 2020-12-12 04:00

    "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();
    }  
    
    0 讨论(0)
  • 2020-12-12 04:06

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-12 04:11

    Try this:

    JSONParser parser = new JSONParser();
    try {
          Object obj = parser.parse(datJ);
          JSONObject jsonObject = (JSONObject) obj;
    
            JSONObject rikeardObject = (JSONObject) jsonObject.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();
        }  
    
    0 讨论(0)
提交回复
热议问题