How to convert HashMap to JsonNode with Jackson?

前端 未结 2 1541
不思量自难忘°
不思量自难忘° 2020-12-24 01:35

I have a HashMap object which I want to convert to JsonNode tree using com.fasterxml.jackson.databind.ObjectMapper. What is the best w

相关标签:
2条回答
  • 2020-12-24 02:10

    The following will do the trick:

    JsonNode jsonNode = mapper.convertValue(map, JsonNode.class);
    

    Or use the more elegant solution pointed in the comments:

    JsonNode jsonNode = mapper.valueToTree(map);
    

    If you need to write your jsonNode as a string, use:

    String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
    
    0 讨论(0)
  • 2020-12-24 02:17

    First transform your map in a JsonNode :

    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNodeMap = mapper.convertValue(myMap, JsonNode.class);
    

    Then add this node to your ObjectNode with the set method :

    myObjectNode.set("myMapName", jsonNodeMap);
    

    To convert from JsonNode to ObjectNode use :

    ObjectNode myObjectNode = (ObjectNode) myJsonNode;
    
    0 讨论(0)
提交回复
热议问题