java中json的嵌套对象

时间:2015-08-19 10:16:05

标签: java json jsonobject

这是我的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" : "12345",
            "name" : "abcde"
        }
        "cd": "afsf"
    }
    ]
}

我想在Java中使用"id"对象"abc"吗? 我创建了一个内容对象,代码在下面

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

如何现在访问java中的"id""name"? 如果有任何语法错误,请忽略...

1 个答案:

答案 0 :(得分:0)

以下代码作为提示来解决您的问题: -

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