问题
This is my JSON file
{
"content": [
{
"a":{
"b" : "abcd",
"c" : "bcd"
}
"ab" : "123",
"abc":{
"id" : "12345",
"name" : "abcde"
}
"cd": "afsf"
},
{
"a":{
"b" : "abcd",
"c" : "bcd"
}
"ab" : "123",
"abc":{
"id" : "12345",
"name" : "abcde"
}
"cd": "afsf"
}
]
}
I want the "id"
of object "abc"
in Java?
I created a object of content and the code is below
JSONArray content = (JSONArray) jsonObject.get("content");
for (int i = 0; i < content.length(); i++) {
JSONObject inner = (JSONObject) content.getJSONObject(i);
String abc = inner.getString("Loan_Application__r");
}
How to i access now the "id"
and "name"
in java?
pls ignore if any syntax mistake is their...
回答1:
Take the below code as a hint to approach your problem:-
public static void main(String[] args){
String json="{ \"content\": [ {\"a\":{ \"b\" : \"abcd\", \"c\" : \"bcd\"},\"ab\" : \"123\",\"abc\":{\"id\" : \"12345\", \"name\" : \"abcde\"},\"cd\": \"afsf\"},{\"a\":{\"b\" : \"abcd\", \"c\" : \"bcd\"},\"ab\" : \"123\",\"abc\":{\"id\" : \"12346\",\"name\" : \"abcde\"},\"cd\": \"afsf\"}]}";
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("content");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject objects = jsonArray.getJSONObject(i);
String[] elementNames = JSONObject.getNames(objects);
for (String elementName : elementNames)
{
if(elementName.equalsIgnoreCase("abc")){
JSONObject value = objects.getJSONObject(elementName);
String[] elementList = JSONObject.getNames(value);
for(String j:elementList){
if(j.equalsIgnoreCase("id")){
System.out.println(value.getString("id"));
}
}
}
}
}
}
Output:-
12345
12346
来源:https://stackoverflow.com/questions/32092668/acess-nested-object-of-json-in-java