Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize using @Jsonview with nested objects

I have a class which holds 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 collection bEntities to be serialized using VerboseViewB.Minimal.

Is there a way to achieve it?

like image 418
kiruba Avatar asked Apr 24 '14 05:04

kiruba


People also ask

How do you access the JSON fields arrays and nested objects of JsonNode in Java?

We can access a field, array or nested object using the get() method of JsonNode class. We can return a valid string representation using the asText() method and convert the value of the node to a Java int using the asInt() method of JsonNode class.

How do I map nested values with Jackson?

To map the nested brandName property, we first need to unpack the nested brand object to a Map and extract the name property. To map ownerName, we unpack the nested owner object to a Map and extract its name property.


1 Answers

you need to change your json view hierachy a little:

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

then you can annotate your classes like

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 you serialize using the view AComplete, the serializer will take the AComplete and MinimalView properties because AComplete extends MinimalView.

like image 158
César Alforde Avatar answered Oct 19 '22 23:10

César Alforde