首页 > 解决方案 > 通过拆分字符串创建 JSON?

问题描述

所以我有一种情况,我从数据库中获取一些我无法更改/更新的数据。所以我来自 2 列的数据是这样的:

例如

        Column1             Column2
Row 1: hello.how.are.you    Gracie
Row 2: hello.how.is.she     John
Row 3: hello.how.is.he      Gurinder   
Row 4: hello.from.me        Singh

所以我需要创建一个如下所示的 JSON:

{  
   "hello":{  
      "how":{  
         "are":{  
            "you":"Gracie"
         },
         "is":{  
            "he":"Gurinder",
            "she":"John"
         }
      },
      "from":{  
         "me":"Singh"
      }
   }
}

我想要一些优化方法来创建我的 JSON。谢谢!

public static void main(String[] args) {

    List<String > stringList = new ArrayList();
    stringList.add("hello.how.are.you");
    stringList.add("hello.how.is.she");
    stringList.add("hello.how.is.he");
    stringList.add("hello.from.me");

    JSONObject response = new JSONObject();

    for (String str : stringList) {

            String[] keys = str.split("\\.");

            for (int i = 0; i < keys.length; i++) {

                if (response.has(keys[i])) {

                } else {
                    JSONObject jsonObject2 = new JSONObject()
                    response.append(keys[i], jsonObject2);

                }
            }
        }
    }

我正在做这样的事情并试图解决。

标签: javajsonspring-restjsonparser

解决方案


您用于输入的内容需要保存所有数据(包括第 2 列)。假设input变量HashMap<String, String>等于

{
    "hello.how.are.you" : "Gracie",
    ...
}

目前,您的代码看起来正在运行中。问题是,response当您想要追加到 JSON 树中的某个值时,您正在追加到 。

JSONObject parent = response;
for(...) {
    // If there's no JSON there, just make it
    if( !parent.has(keys[i]) ) {
        // It's not already in there, so let's make it
        parent.put(keys[i], new JSONObject()); // response["hello"] = {}
    }
    // Now, look at how this works. If keys = ["hello", "how", "are", "you"],
    // Then when i == 0, parent <= response["hello"]
    // That way you do response["hello"].append("how", {}) on the next iteration
    parent = (JSONObject)parent.get(keys[i]);
}

您还需要处理尾箱,您可以使用类似

if( i == keys.length - 1 ) {
    parent.put(keys[i], input.get(str)); // str = "hello.how.are.you"
    // input.get("hello.how.are.you") == "Gracie"
} else ...

推荐阅读