java中json的访问嵌套对象 [英] acess nested object of json in java

查看:150
本文介绍了java中json的访问嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的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中对象"abc""id"吗? 我创建了一个内容对象,代码在下面

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

我现在如何在Java中访问"id""name"? 请忽略是否有语法错误是他们的...

How to i access now the "id" and "name" in java? pls ignore if any syntax mistake is their...

推荐答案

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

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

这篇关于java中json的访问嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆