java - 如何将点表示法 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 上没有这样的问题。
解决方案
回答我自己的问题:
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);
}
}
}
推荐阅读
- batch-file - 如何复制文件名中带有欧元符号的最新文件?
- azure - 如何将 TensorFlow Serving 作为 Azure 容器实例运行并传递 docker 命令
- java - 什么是类比
我想使用 java DSL重写以下cuda - 如何在 CUDA 中的条件 while 语句中同步 warp 中的线程?
- android - Facebook Android SDK,graph api >3.2 和 4.0 发送应用请求问题
- python - Flask 循环导入问题 - 将变量从 __init__.py 导入视图
- android - 在您输入空格之前,TextArea 不会接收文本
- android - Android / 更改特定微调器项目中的文本
- lucene - 在 lucene 中,如何从搜索查询中查找仅包含单词的文档
- node.js - 无法使用节点 http 模块获取对实时网站 URL 的 http 请求的响应