且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Jackson序列化为java.util.List和java.util.Map

更新时间:2023-09-11 23:24:52

使用convertValue方法:

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

对于Object.class作为目标类型它也很好:

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);

打印:

{name=Rick, lastName=Bricky}
[{name=Rick, lastName=Bricky}]