How to serialize using @Jsonview with nested objects

前端 未结 3 1358
Happy的楠姐
Happy的楠姐 2021-01-04 08:49

I have a class which holds a collection of another class.

class A{
 @JsonView(VerboseViewA.Minimal.class)
 String field1;
 @JsonView(VerboseViewA.Complete.c         


        
3条回答
  •  醉梦人生
    2021-01-04 09:30

    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 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
    {
        @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.

    提交回复
    热议问题