java - 通过分割字符串创建 JSON?

标签 java json spring-rest jsonparser

所以我遇到一种情况,我从数据库中获取一些无法更改/更新的数据。所以我的两列数据如下:

例如:

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

                }
            }
        }
    }

我正在做类似的事情并试图解决。

最佳答案

您用于输入的内容需要保存所有数据(包括第 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 ...

关于java - 通过分割字符串创建 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51676823/

相关文章:

java - 是否有一种快速方法可以从任何集合/映射中获取与条件列表之一匹配的所有元素?

json - NSJSONSerialization 不处理负整数

javascript - 从用户输入的属性和值中添加/更新 json 对象

java - 如何使用@XmlElement注释将REST输出映射到Spring Boot中的Dto,以便我可以获得所需格式的xml输出?

java - 无法使用 Spring Boot REST 存储库在 H2 DB 中创建记录

java - 运行 junit 测试时出现 ZipException

java - 当加载后属性文件不存在时,使用外部属性文件的属性

java.util.NoSuchElementException - 扫描仪读取用户输入

javascript - 解析 JSON 字符串的问题

java - 在运行时更改表 - Spring API Rest