Get Key and values from JSONObject

前端 未结 3 1091
半阙折子戏
半阙折子戏 2020-12-18 02:30

I am trying to extract Key and values from my JSONObject. But i am not able to do that. Here is the JSON:

[{\"id\":[\"5\"]},{\"Tech\":[\"Java\"]}]

相关标签:
3条回答
  • 2020-12-18 02:48

    Parameter you are sending is JsonArray and referring to JsonObject. The Correct way is

    JSONObject jsonObj = new JSONObject("{'id':['5','6']},{'Tech':['Java']}");      
        System.out.println(jsonObj.getString("id"));
    
        JSONArray jsonArray = new JSONArray("[{'id':['5','6','7','8']},{'Tech':['Java']}]");
        System.out.println(jsonArray.length());
        for(int i=0;i<jsonArray.length();i++){
                System.out.println(jsonArray.getJSONObject(i).getString("id"));
        }
    
    0 讨论(0)
  • 2020-12-18 02:57

    Because at id you dont have a string , you have a array of string ,

    so insted of doing this jsonObj.getString("id");

    do this

    jsonObj.getArray("id"); this will give you that array in return

    like if you have a Json Array at id then you have to do this

    jsonObj.getJSONArray("id");

    0 讨论(0)
  • 2020-12-18 03:05

    Try this:

    try {
        JSONArray jsonArr = new JSONArray("[{\"id\":[\"5\"]},{\"Tech\":[\"Java\"]}]");
    
        for (int i = 0; i < jsonArr.length(); i++) {
            JSONObject jsonObj = jsonArr.getJSONObject(i);
            String k = jsonObj.keys().next();
            Log.i("Info", "Key: " + k + ", value: " + jsonObj.getString(k));
        }
    
    } catch (JSONException ex) {
        ex.printStackTrace();
    }
    
    0 讨论(0)
提交回复
热议问题