Is there any way to convert a Map to a JSON representation using Jackson without writing to a file?

后端 未结 2 1937
野趣味
野趣味 2020-12-10 10:03

I\'m trying to use Jackson to convert a HashMap to a JSON representation.

However, all the ways I\'ve seen involve writing to a file and then reading it back, which

2条回答
  •  -上瘾入骨i
    2020-12-10 10:48

    Pass your Map to ObjectMapper.writeValueAsString(Object value)

    It's more efficient than using StringWriter, according to the docs:

    Method that can be used to serialize any Java value as a String. Functionally equivalent to calling writeValue(Writer,Object) with StringWriter and constructing String, but more efficient.

    Example

    import org.codehaus.jackson.map.ObjectMapper;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    
    public class Example {
    
        public static void main(String[] args) throws IOException {
            Map map = new HashMap<>();
            map.put("key1","value1");
            map.put("key2","value2");
    
            String mapAsJson = new ObjectMapper().writeValueAsString(map);
            System.out.println(mapAsJson);
        }
    }
    

提交回复
热议问题