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
Vytenis Bivainis
  • 2,308
  • 21
  • 28

1 Answers1

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}]
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • `mapper.convertValue(object, Object.class)` also works. – Vytenis Bivainis Mar 19 '19 at 22:51
  • 1
    @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! – Michał Ziober Mar 19 '19 at 22:56