Java 如何使用 Jackson 将 HashMap 转换为 JsonNode?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39391095/
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
How to convert HashMap to JsonNode with Hymanson?
提问by cacert
I have a HashMap
object which I want to convert to JsonNode
tree using com.fasterxml.Hymanson.databind.ObjectMapper
. What is the best way to do it?
我有一个HashMap
对象,我想JsonNode
使用com.fasterxml.Hymanson.databind.ObjectMapper
. 最好的方法是什么?
I found the following code but since I don't know the Hymanson API well, I wonder if there are some better ways.
我找到了以下代码,但由于我不太了解 Hymanson API,我想知道是否有更好的方法。
mapper.reader().readTree(mapper.writeValueAsString(hashmap))
采纳答案by cassiomolin
The following will do the trick:
以下将解决问题:
JsonNode jsonNode = mapper.convertValue(map, JsonNode.class);
Or use the more elegantsolution pointed in the comments:
或者使用评论中指出的更优雅的解决方案:
JsonNode jsonNode = mapper.valueToTree(map);
If you need to write your jsonNode
as a string, use:
如果您需要将您的写jsonNode
为字符串,请使用:
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
回答by Laurent
First transform your map in a JsonNode :
首先在 JsonNode 中转换您的地图:
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNodeMap = mapper.convertValue(myMap, JsonNode.class);
Then add this node to your ObjectNode with the set method :
然后使用 set 方法将此节点添加到您的 ObjectNode :
myObjectNode.set("myMapName", jsonNodeMap);
To convert from JsonNode to ObjectNode use :
要将 JsonNode 转换为 ObjectNode,请使用:
ObjectNode myObjectNode = (ObjectNode) myJsonNode;