After struggling with the same problem, I came up to this solution:
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;
}
Now when serializing an instance of class A using VerboseViewA.Complete.class, bEnitities will be included and serialized using a custom VerboseMinimalSerializer, overriding its 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);
}
}
Notice this custom serializer is using the view VerboseViewB.Minimal.class.