1

Is it possible to serialize Java objects to lists and maps with Jackson library directly? I mean not to String, not to byte[], but to java.util.Map and java.util.List.

This might be helpful when filtering out unnecessary fields dynamically.

I can do it in two steps, by first converting to String.

ObjectMapper mapper = new ObjectMapper()
DTO dto = new DTO();
DTO[] dtos = {dto};
mapper.readValue(mapper.writeValueAsString(dto), Object.class); // Map
mapper.readValue(mapper.writeValueAsString(dtos), Object.class); // List

1 Answer 1

2

Use convertValue method:

ObjectMapper objectMapper = new ObjectMapper();
Map map = objectMapper.convertValue(new Person(), Map.class);
System.out.println(map);

It works as well for Object.class as a target type:

ObjectMapper objectMapper = new ObjectMapper();
Object map = objectMapper.convertValue(new Person(), Object.class);
Object array = objectMapper.convertValue(Collections.singleton(new Person()), Object.class);
System.out.println(map);
System.out.println(array);

prints:

{name=Rick, lastName=Bricky}
[{name=Rick, lastName=Bricky}]
Sign up to request clarification or add additional context in comments.

2 Comments

mapper.convertValue(object, Object.class) also works.
@VytenisBivainis, It is a little bit counterintuitive but if you need this level of abstraction and it works for you why not. I will add it to an answer. I always used Map and List as target classes but today I learned it works as expected for Object.class as well. Thanks, I learned something new too!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.