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