在遇到同样的问题后,我想出了这个解决方案:
class A
{
@JsonView(VerboseViewA.Minimal.class)
String field1;
@JsonView(VerboseViewA.Complete.class)
String field2;
@JsonView(VerboseViewA.Complete.class)
@JsonSerialize(using = VerboseMinimalSerializer.class)
Collection<B> bEntities;
}
class B
{
@JsonView(VerboseViewB.Minimal.class)
String field2;
@JsonView(VerboseViewB.Complete.class)
String field3;
}
现在,当使用 VerboseViewA.Complete.class 序列化类 A 的实例时,bEnitities 将被包含并使用自定义 VerboseMinimalSerializer 序列化,覆盖其 JsonView:
public class VerboseMinimalSerializer extends JsonSerializer<Object>
{
@Override
public void serialize(Object object, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException
{
ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.setConfig(mapper.getSerializationConfig().withView(VerboseViewB.Minimal.class));
jsonGenerator.setCodec(mapper);
jsonGenerator.writeObject(object);
}
}
请注意,此自定义序列化程序正在使用视图 VerboseViewB.Minimal.class。