How to convert HashMap to JsonNode with Jackson?

前端 未结 2 1540
不思量自难忘°
不思量自难忘° 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);
    

提交回复
热议问题