假设您有一个具有许多字段的对象 A,其中一个字段是唯一标识该对象的 id。在我的java代码中,有一个对象B,它以类似于此代码的几个数据结构保存这些对象:
private List<A> all;
private Map<Long, A> mapped;
现在,当将 B 序列化为 json 时,我只希望列表 all
中的对象 A 使用所有字段进行序列化,而映射 mapped
中的对象仅使用 id 字段进行序列化。你会怎么做?
最佳答案
您可以实现StdConverter接口(interface):
public class YourConverter implements StdConverter<Map<Long, A>, Map<Long, String>> {
@Override
public Map<Long, String> convert(final Map<Long, A> inMap) {
final HashMap<Long, String> outMap = new HashMap<>();
inMap.forEach((k, v) -> outMap.put(k, v.getId()));
return outMap;
// Or as one-liner
// return inMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().getId()));
}
}
然后您可以将转换器添加为 JsonSerialize 注释:
private List<A> all;
@JsonSerialize(converter = YourConverter.class)
private Map<Long, A> mapped;
关于java - Jackson JSON - 用不同的逻辑序列化相同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49572922/