简体   繁体   中英

How to serialize to java.util.List and java.util.Map with Jackson

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

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}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM