Possible to configure Jackson-Json Mapper to exclude properties based on which object it is serializing?

StackOverflow https://stackoverflow.com/questions/2507768

  •  22-09-2019
  •  | 
  •  

Question

Say I have objects such as a Business with a List of Address objects, and an Order that has a Business.

Is it possible to configure so that when the Order is serialized it excludes the list of addresses from the Business object, and when the business is serialized it includes the list?

I'm using ajax to pull data for an RIA and when working with the Order I don't really care about the address data, but when dealing with Business I do want the list.

I'm also using Hibernate for persistence so this is really an efficiency and performance optimization.

Was it helpful?

Solution

If I understand question correctly, yes, I think JSON Views for Jackson would allow this. You would basically create two different views (profiles) for same type, and choose which one to use for serialization.

OTHER TIPS

You could use the JsonIgnore Annotation to ignore the Address list in serialization and switch off the use of annotations in the ObjectMapper's SerializationConfig when serializing a Business. Of course, this means that other annotations you might use are ignored as well. Not perfect, but you might find a better solution looking into this, hope it helps (obviously).

ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().disable(Feature.USE_ANNOTATIONS);

Yes, you can do it. All you need is to declare the List of Address as transient property in you business object.

Then add the following code to your jsonConfig:

jsonConfig.setIgnoreTransientFields(true);
@JsonIgnore 

is used to ignore properties that you don't want to convert to json.

public class UserDocument {

    private long id;

    private String documentUrl;

    @JsonIgnore
    private byte documentType;

    //traditional getters and setters
}

Output: This will convert the properties id and documentUrl but will not convert property documentType.

{
  "id": 5,
  "document_url": "/0/301115124948.jpg"
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top