英文:
How to convert dot notation JsonObject to nested JsonObject in Java?
问题
{
"ab": {
"cd": {
"e": "foo",
"f": "bar"
},
"g": "foo2"
}
}
英文:
I want to convert this JSON:
{
"ab.g": "foo2",
"ab.cd.f": "bar",
"ab.cd.e": "foo"
}
to this:
{
"ab": {
"cd": {
"e": "foo",
"f": "bar"
},
"g": "foo2"
}
}
I have found this: Convert javascript dot notation object to nested object but the accepted answer on this post has some language specific syntax and I am not able to rewrite the same logic in Java.
Note: There is no attempt in the question because I have answered this myself - because there is no such question on stackoverflow for Java specifically.
答案1
得分: 3
以下是翻译好的部分:
回答自己的问题:
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);
}
}
}
英文:
Answering my own question:
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);
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论