Reputation: 2376
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
Upvotes: 1
Views: 62
Reputation: 38625
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}]
Upvotes: 2