【问题标题】:How to convert dot notation JsonObject to nested JsonObject in Java?如何将点表示法 JsonObject 转换为 Java 中的嵌套 JsonObject?
【发布时间】:2020-09-26 23:50:10
【问题描述】:

我想转换这个 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 但accepted answer on this post 有一些特定于语言的语法,我无法用 Java 重写相同的逻辑。

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

【问题讨论】:

    标签: java


    【解决方案1】:

    回答我自己的问题:

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

    【讨论】:

    • 非常有用,当您尝试打印返回类型为 void 的函数时,只需从 main 方法中删除 System.out.println 语句
    • 正是我想要的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 2011-07-11
    • 2020-01-12
    • 1970-01-01
    • 2016-05-14
    相关资源
    最近更新 更多