【问题标题】:Iterating through nested complex json object遍历嵌套的复杂 json 对象
【发布时间】:2017-10-16 20:59:07
【问题描述】:

我正在读取一个具有动态结构的 JSON 字符串。 JSON 可能有一个对象和对象数组,或者两者都有,或者只有键值。

我试图遍历所有的可能性,我知道,阅读。

我需要读取整个字符串而不会丢失任何节点/密钥对。

以下是 JSON 的示例:

{
  "cityId": {
    "city": "Old Delhi",
    "cityId": "CTY2",
    "stateId": "STE1",
    "statusId": "STA1",
    "userId": "ONB1"
  },
  "emailId": "ud.r@gmail.com",
  "firstName": "Udit",
  "lastName": "R",
  "password1": "xxxxxx",
  "password2": "xxxxxx",
  "statusId": {
    "status": "ACTIVE",
    "statusId": "STA1"
  },
  "userId": "ONB2",
  "userInfoId": {
    "deptId": {
      "deptId": "DPT2",
      "deptName": "HR",
      "statusId": "STA1",
      "userId": "ONB1"
    },
    "roleId": {
      "roleId": "RLE2",
      "roleName": "Member",
      "statusId": "STA1",
      "userId": "ONB1"
    },
    "statusId": {
      "status": "ACTIVE",
      "statusId": "STA1"
    },
    "userId": "ONB2",
    "userInfoId": "UIN2"
  }
}

我当前的 Java 方法:

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import java.io.IOException;
import java.util.Iterator;
import org.json.JSONObject;

// Omittded class definiton, just the method
public void getRSDataFromMethodTwo(String url) throws IOException {
    // Initiate client and do JSON request
    Client client = Client.create();
    WebResource webResource = client.resource(url);        
    ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
    if (response.getStatus() != 200) 
    {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }
    String output = response.getEntity(String.class);
    System.out.println("Response===get=" + output);

    // Parse JSOn
    JSONObject json = new JSONObject(output);
    Iterator<String> iterator = json.keys();               

    System.out.println("Fields:");
    while (iterator.hasNext()) 
    {
        String x = iterator.next().toString();
        System.out.println(" Keys " + x);                        
    }

    iterator = json.keys();
    while (iterator.hasNext()) 
    {
        String key = iterator.next();
        System.out.println(key + " : " + json.get(key));
        if (json.get(key).toString().startsWith("{")) 
        {                
            JSONObject childJson = new JSONObject(json.get(key).toString());                               
            Iterator<String> childIterator = childJson.keys();
            if (childIterator.hasNext()) 
            {                                        
                while (childIterator.hasNext()) 
                {
                    String chKey = childIterator.next();
                    System.out.println("Child Key "+chKey+ " : "+childJson.get(chKey));                        
                }
            }
        }            
    }
}

还有输出:

Info:   firstName : Udit
Info:   lastName : Ranjan
Info:   statusId : {"statusId":"STA1","status":"ACTIVE"}
Info:   Child Key statusId : STA1
Info:   Child Key status : ACTIVE
Info:   emailId : ud.r@gmail.com
Info:   password2 : xxxxxx
Info:   cityId : {"statusId":"STA1","city":"Old Delhi","stateId":"STE1","cityId":"CTY2","userId":"ONB1"}
Info:   Child Key statusId : STA1
Info:   Child Key city : Old Delhi
Info:   Child Key stateId : STE1
Info:   Child Key cityId : CTY2
Info:   Child Key userId : ONB1
Info:   password1 : b2b123
Info:   userId : ONB2
Info:   userInfoId : {"statusId":{"statusId":"STA1","status":"ACTIVE"},"roleId":{"statusId":"STA1","roleId":"RLE2","roleName":"Member","userId":"ONB1"},"deptId":{"deptName":"HR","statusId":"STA1","deptId":"DPT2","userId":"ONB1"},"userId":"ONB2","userInfoId":"UIN2"}
Info:   Child Key statusId : {"statusId":"STA1","status":"ACTIVE"}
Info:   Child Key roleId : {"statusId":"STA1","roleId":"RLE2","roleName":"Member","userId":"ONB1"}
Info:   Child Key deptId : {"deptName":"HR","statusId":"STA1","deptId":"DPT2","userId":"ONB1"}
Info:   Child Key userId : ONB2
Info:   Child Key userInfoId : UIN2

编辑-因为我无法读取嵌套对象,例如子键 deptId,因为它是动态字符串,我不知道哪个对象具有嵌套对象。

【问题讨论】:

  • 该输出实际上缺少什么?它有什么问题?
  • 我强烈推荐使用 Jackson。有了这个,你可以设计一个包装 POJO 可以进来的东西,它会自动将整个动态 json 反序列化为你可以交互的 POJO。

标签: java json


【解决方案1】:

看看将 Jackson 库与 @JsonAnySetter 一起使用 http://www.cowtowncoder.com/blog/archives/2011/07/entry_458.html

【讨论】:

    猜你喜欢
    • 2018-05-13
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多