How to serialize using @Jsonview with nested objects

I have a class that contains a collection of another class.

class A{ @JsonView(VerboseViewA.Minimal.class) String field1; @JsonView(VerboseViewA.Complete.class) String field2; @JsonView(VerboseViewA.Complete.class) Collection<B> bEntities; } class B{ @JsonView(VerboseViewB.Minimal.class) String field2; @JsonView(VerboseViewB.Complete.class) String field3; } 

When I serialize Class A using VerboseViewA.Complete, I want the bEntities collection to be serialized using VerboseViewB.Minimal.

Is there any way to achieve it?

+7
java spring jackson
source share
3 answers

This solves my problem. I am not sure if there is a better way to solve this problem.

  class A{ @JsonView(VerboseViewA.Minimal.class) String field1; @JsonView(VerboseViewA.Complete.class) String field2; @JsonView(VerboseViewA.Complete.class) Collection<B> bEntities; } class B{ @JsonView({VerboseViewA.Complete.class,VerboseViewB.Minimal.class}) String field2; @JsonView(VerboseViewB.Complete.class) String field3; } 
+5
source share

After struggling with the same problem, I came up with 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 it with 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); } } 

Note that this custom serializer uses the VerboseViewB.Minimal.class view.

+3
source share

you need to change your jovachy jsonach a bit:

 public class MinimalView { }; public class AComplete extends MinimalView { }; public class BComplete extends MinimalView { }; 

then you can annotate your classes e.g.

 class A{ @JsonView(MinimalView.class) String field1; @JsonView(AComplete.class) String field2; @JsonView(AComplete.class) Collection<B> bEntities; } class B{ @JsonView(Minimal.class) String field2; @JsonView(BComplete.class) String field3; } 

when serializing using the AComplete view, the serializer will use the AComplete and MinimalView properties, since AComplete extends the MinimalView.

+2
source share

All Articles