在 Java 中使用 Jackson 创建 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40967921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create JSON object using Hymanson in Java
提问by Shashank Shekher
I need to create a JSON string as below using Hymanson. I know similar question has been answered already here: Creating a json object using Hymanson
我需要使用 Hymanson 创建一个 JSON 字符串,如下所示。我知道这里已经回答了类似的问题: Creating a json object using Hymanson
But my expected JSON string is a little different from the one in above example.
但是我预期的 JSON 字符串与上面示例中的字符串略有不同。
How can I form the below formatted JSON object in Java using only Hymanson? Also, I do not prefer creating a separate POJO to achieve this.
如何仅使用 Hymanson 在 Java 中形成以下格式的 JSON 对象?此外,我不喜欢创建一个单独的 POJO 来实现这一点。
Expected Output:
预期输出:
{
"obj1": {
"name1": "val1",
"name2": "val2"
},
"obj2": {
"name3": "val3",
"name4": "val4"
},
"obj3": {
"name5": "val5",
"name6": "val6"
}
}
采纳答案by Sach141
Try this:
尝试这个:
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.createObjectNode();
JsonNode childNode1 = mapper.createObjectNode();
((ObjectNode) childNode1).put("name1", "val1");
((ObjectNode) childNode1).put("name2", "val2");
((ObjectNode) rootNode).set("obj1", childNode1);
JsonNode childNode2 = mapper.createObjectNode();
((ObjectNode) childNode2).put("name3", "val3");
((ObjectNode) childNode2).put("name4", "val4");
((ObjectNode) rootNode).set("obj2", childNode2);
JsonNode childNode3 = mapper.createObjectNode();
((ObjectNode) childNode3).put("name5", "val5");
((ObjectNode) childNode3).put("name6", "val6");
((ObjectNode) rootNode).set("obj3", childNode3);
String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
System.out.println(jsonString);