您可以创建一个从Foo
class 扩展的类,以提供fooList
使用 annotation的替代序列化@JsonGetter
,例如包装器。
Foo
班级:
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
是Foo
序列化的包装器,它有一个转换Lst<Foo>
为 List< FooFooJsonSimplifiedSerializationWrapper
> 的方法,您必须在序列化之前的某个时间点调用该方法:
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
with @JsonView
annotation 和自定义视图以使序列化适应您的需求,但我认为这是一个更麻烦的解决方案。