example json
String response =
"{
"data":{
"getData":[
{
"key1":"value1"
"key2":"value2"
"key3":"value3"
},
{
"key1":"value11"
"key2":"value21"
"key3":"value31"
}
]
}
}";
JSONObject jsonObject = new JSONObject(response);
String str= jsonObject.getString("key3");
im getting below error
org.json.JSONException: JSONObject["key3"] not found.
pls help how to get value of key3 with two diff values - value3 and value31
CodePudding user response:
To retrieve key3
you need to go to the nested objects:
String response = "{\n"
" \"data\": {\n"
" \"getData\": [\n"
" {\n"
" \"key1\": \"value1\",\n"
" \"key2\": \"value2\",\n"
" \"key3\": \"value3\"\n"
" },\n"
" {\n"
" \"key1\": \"value11\",\n"
" \"key2\": \"value21\",\n"
" \"key3\": \"value31\"\n"
" }\n"
" ]\n"
" }\n"
"}";
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("getData");
int length = jsonArray.length();
for (int i = 0; i < length; i ) {
System.out.println(jsonArray.getJSONObject(i).get("key3"));
}