首页 > 解决方案 > 如何将点表示法 JsonObject 转换为 Java 中的嵌套 JsonObject?

问题描述

我想转换这个 JSON:

{
    "ab.g": "foo2",
    "ab.cd.f": "bar",
    "ab.cd.e": "foo"
}

对此:

{
   "ab": {
      "cd": {
         "e": "foo",
         "f": "bar"
      },
      "g": "foo2"
   }
}

我发现了这一点:Convert javascript dot notation object to nested object,但这篇文章中接受的答案有一些特定于语言的语法,我无法用 Java 重写相同的逻辑。

注意:这个问题没有尝试,因为我自己已经回答了这个问题 - 因为在 Java 的 stackoverflow 上没有这样的问题。

标签: java

解决方案


回答我自己的问题:

import io.vertx.core.json.JsonObject;

public class Tester {
    public static void main(String[] args) {
        JsonObject jsonObject = new JsonObject();
        deepenJsonWithDotNotation(jsonObject, "ab.cd.e", "foo");
        deepenJsonWithDotNotation(jsonObject, "ab.cd.f", "bar");
        deepenJsonWithDotNotation(jsonObject, "ab.g", "foo2");
    }

    private static void deepenJsonWithDotNotation(JsonObject jsonObject, String key, String value) {
        if (key.contains(".")) {
            String innerKey = key.substring(0, key.indexOf("."));
            String remaining = key.substring(key.indexOf(".") + 1);

            if (jsonObject.containsKey(innerKey)) {
                deepenJsonWithDotNotation(jsonObject.getJsonObject(innerKey), remaining, value);
            } else {
                JsonObject innerJson = new JsonObject();
                jsonObject.put(innerKey, innerJson);
                deepenJsonWithDotNotation(innerJson, remaining, value);
            }
        } else {
            jsonObject.put(key, value);
        }
    }
}

推荐阅读