user7637864
user7637864

Reputation: 237

Get Key and values from JSONObject

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"]}]

It is a String initially. I have converted that to JSONObject using :

JSONObject jsonObj = new JSONObject("[{"id":["5"]},{"Tech":["Java"]}]");

Then i am trying to get the key and value by:

jsonObj.getString("id");

But its giving me null. Can anyone help me out here?

Upvotes: 11

Views: 104467

Answers (3)

AG_
AG_

Reputation: 54

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

Upvotes: 2

Wajih
Wajih

Reputation: 4393

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

Upvotes: 12

Vipin Chaudhary
Vipin Chaudhary

Reputation: 444

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

Upvotes: -1

Related Questions