【问题标题】:java using JSONObject to loop recursive through any jsondatajava使用JSONObject循环遍历任何jsondata
【发布时间】:2022-08-10 00:02:02
【问题描述】:

我将 json 字符串读入 java 中的 JSONObject。 json-String 变化:

这是一个json:

{\"menu\": {
  \"id\": \"file\",
  \"value\": \"File\",
  \"popup\": {
    \"menuitem\": [
      {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},
      {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"},
      {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}
    ]
  }
}}

如果我在 5 分钟后得到它,这也是一样的:

{\"menu\": {
  \"id\": \"file\",
  \"popup\": {
    \"menuitem\": [
      {\"master\": \"New\", \"onclick\": \"CreateNewDoc()\"},
    ]
  }
}}

json 的结构与第一个不同。我无法更改服务器端。这是在项目中给出的。

所以我喜欢在不知道键的情况下创建存储在 json 中的所有值的列表:

Key, Value
menu-id, file
menu-value, File
menu-popup-menuitem-0-value, New
menu-popup-menuitem-0-onclick, CreateNewDoc
...

但是如果我使用 JSONObject 我必须知道密钥。我没有找到任何循环遍历所有元素的功能?

有人可以帮忙吗?

这是我的代码:

Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), \"UTF-8\"));
        
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0;)
   sb.append((char)c);
                    
String response = sb.toString();
JSONObject json_response = new JSONObject(response);
how to loop throug json_response to get each key/value and check if it has elements below????

    标签: java json


    【解决方案1】:

    JSONObject 就像一个 java.util.Map,即使它没有实现接口。即使您事先不知道它们,您也可以获取所有键并遍历它们。

    jsonObject.keySet()
    

    这将返回 Set,由对象中的键组成。现在递归函数:

        private static void recursiveTraverse(String previousKey, JSONObject currentObject) {
        //iterate each key
        for (String currentKey : currentObject.keySet()) {
          //build the next key
          String nextKey = previousKey == null || previousKey.isEmpty() ? currentKey : previousKey + "-" + currentKey;
          Object value = currentObject.get(currentKey);
          if (value instanceof JSONObject) {
            //if current value is object, call recursively with next key and value
            recursiveTraverse(nextKey, (JSONObject) value);
          } else if (value instanceof JSONArray) {
            //if current value is array, iterate it
            JSONArray array = (JSONArray) value;
            for (int i = 0; i < array.length(); i++) {
              Object object = array.get(i);
              JSONObject jsonObject = (JSONObject) object;
              //assuming current array member is object, call recursively with next key + index and current member
              recursiveTraverse(nextKey + "-" + i, jsonObject);
              //you might need to handle special case of current member being array
            }
          } else {
            //value is neither object, nor array, so we print and this ends the recursion
            System.out.println(nextKey + ", " + value);
          }
        }
      }
    

    开始遍历对象:

    JSONObject jsonObject = new JSONObject(jsonString);
    recursiveTraverse("", jsonObject);
    

    它适用于大多数用例,但正如我在代码中的 cmets 中指出的那样,它不处理当前数组元素是另一个数组的情况。如果您的约束允许这样做,您可能必须为此实现递归函数。像这样的东西:

      private static void recursiveHandleArray(String prevKey, JSONArray currentArray) {
        //implement
      }
    

    【讨论】:

      【解决方案2】:

      改变这个:

      //if current value is array, iterate it
      JSONArray array = (JSONArray) value;
      for (int i = 0; i < array.length(); i++) {
        Object object = array.get(i);
        JSONObject jsonObject = (JSONObject) object;
        //assuming current array member is object, call recursively with next key + index and current member
        recursiveTraverse(nextKey + "-" + i, jsonObject);
        //you might need to handle special case of current member being array
      }
      

      对此:

           //if current value is array, iterate it
      JSONArray array = (JSONArray) value;
      for (int i = 0; i < array.length(); i++) {
          Object object = array.get(i);
          if (object instanceof JSONObject) {
              JSONObject jsonObject = (JSONObject) object;
              //assuming current array member is object, call recursively with next key + index and current member
              recursiveTraverse(nextKey + "." + i, jsonObject);
          } else {
              //value is neither object, nor array, so we print and this ends the recursion
              System.out.println(nextKey + ", " + object);
          }
      }
      

      解决了当前数组成员为对象时的问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-27
        • 1970-01-01
        • 1970-01-01
        • 2014-03-22
        • 2013-04-05
        • 1970-01-01
        相关资源
        最近更新 更多