How to access nested elements of json object using getJSONArray method
You have to decompose the full object to reach the entry
array.
Assuming REPONSE_JSON_OBJECT
is already a parsed JSONObject
.
REPONSE_JSON_OBJECT.getJSONObject("result")
.getJSONObject("map")
.getJSONArray("entry");
I suggest you to use Gson library. It allows to parse JSON string into object data model. Please, see my example:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
public class GsonProgram {
public static void main(String... args) {
String response = "{\"result\":{\"map\":{\"entry\":[{\"key\":{\"@xsi.type\":\"xs:string\",\"$\":\"ContentA\"},\"value\":\"fsdf\"},{\"key\":{\"@xsi.type\":\"xs:string\",\"$\":\"ContentB\"},\"value\":\"dfdf\"}]}}}";
Gson gson = new GsonBuilder().serializeNulls().create();
Response res = gson.fromJson(response, Response.class);
System.out.println("Entries: " + res.getResult().getMap().getEntry());
}
}
class Response {
private Result result;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
@Override
public String toString() {
return result.toString();
}
}
class Result {
private MapNode map;
public MapNode getMap() {
return map;
}
public void setMap(MapNode map) {
this.map = map;
}
@Override
public String toString() {
return map.toString();
}
}
class MapNode {
List<Entry> entry = new ArrayList<Entry>();
public List<Entry> getEntry() {
return entry;
}
public void setEntry(List<Entry> entry) {
this.entry = entry;
}
@Override
public String toString() {
return Arrays.toString(entry.toArray());
}
}
class Entry {
private Key key;
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
@Override
public String toString() {
return "[key=" + key + ", value=" + value + "]";
}
}
class Key {
@SerializedName("$")
private String value;
@SerializedName("@xsi.type")
private String type;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
return "[value=" + value + ", type=" + type + "]";
}
}
Program output:
Entries: [[key=[value=ContentA, type=xs:string], value=fsdf], [key=[value=ContentB, type=xs:string], value=dfdf]]
If you not familiar with this library, then you can find a lot of informations in "Gson User Guide".
Try this code using Gson library and get the things done.
Gson gson = new GsonBuilder().create();
JsonObject job = gson.fromJson(JsonString, JsonObject.class);
JsonElement entry=job.getAsJsonObject("results").getAsJsonObject("map").getAsJsonArray("entry");
String str = entry.toString();
System.out.println(str);