acess nested object of json in java

情到浓时终转凉″ 提交于 2019-12-12 03:18:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!