您可以创建一个扩展自
Foo
为提供可选序列化的类
fooList
使用注释
@JsonGetter
就像包装纸一样。
福
班级:
public class Foo implements Serializable {
private int id;
private List<Foo> fooList;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<Foo> getFooList() {
return fooList;
}
public void setFooList(List<Foo> fooList) {
this.fooList = fooList;
}
}
Bar
班级:
public class Bar implements Serializable {
public List<FooJsonSimplifiedSerializationWrapper> fooList;
public List<FooJsonSimplifiedSerializationWrapper> getFooList() {
return fooList;
}
public void setFooList(List<FooJsonSimplifiedSerializationWrapper> fooList) {
this.fooList = fooList;
}
}
FooFooJsonSimplifiedSerializationWrapper
是
福
用于序列化的包装,它有一个要从中转换的方法
Lst<Foo>
列出;
Foofookson简化序列包装器
>在序列化之前,必须在某个时间点调用:
public class FooJsonSimplifiedSerializationWrapper extends Foo {
@JsonGetter("fooList")
public List<Integer> serializeFooList() {
return this.getFooList().stream().map(f -> f.getId()).collect(Collectors.toList());
}
public static List<FooJsonSimplifiedSerializationWrapper> convertFromFoo(List<Foo> fooList) {
return fooList.stream().map(f -> {
FooJsonSimplifiedSerializationWrapper fooSimplified = new FooJsonSimplifiedSerializationWrapper();
BeanUtils.copyProperties(f, fooSimplified);
return fooSimplified;
}).collect(Collectors.toList());
}
}
Main
通过一些测试:
public static void main(String[] args) throws IOException {
Foo foo = new Foo();
foo.setId(1);
Foo fooChild = new Foo();
fooChild.setId(2);
fooChild.setFooList(new ArrayList<>());
Foo fooChild2 = new Foo();
fooChild2.setId(3);
fooChild2.setFooList(new ArrayList<>());
foo.setFooList(Arrays.asList(fooChild, fooChild2));
Bar bar = new Bar();
bar.setFooList(FooJsonSimplifiedSerializationWrapper.convertFromFoo(Arrays.asList(foo)));
System.out.println(new ObjectMapper().writeValueAsString(foo));
System.out.println(new ObjectMapper().writeValueAsString(bar));
}
此代码将打印:
Foo serialization: {"id":1,"fooList":[{"id":2,"fooList":[]},{"id":3,"fooList":[]}]}
Bar serialization: {"fooList":[{"id":1,"fooList":[2,3]}]}
另一个解决方案可能涉及使用
Views
具有
@JsonView
注释和定制视图以适应您的需要,但在我看来是一个更麻烦的解决方案。