Serialize object as Map instead of String using Jackson databind?
Normally one does something like this when you want to serialize an object to a JSON string:
String json = objectMapper.writeValueAsString(myObject);
I wonder if it’s possible to serialize an object directly into a java.util.Map
instead of a String? I.e. something like this (pseudo code):
String json = objectMapper.writeValueAs(myObject, new TypeReference<Map<String,Object>>() {});
I know I can serialize the object to a String first and then deserialize it as a Map<String,Object>
but I’m asking if there’s is a way to do this without first serializing to a String?
I’m using Jackson 2.11.1.
You can use convertValue method of ObjectMapper to convert Object into Map
Map<String, Object> map = objectMapper.convertValue(myObject, Map.class);