简体   繁体   中英

JSON serialization of different attributes of a single entity for different requests using Jackson

There are several REST calls that require the same JSON entity with a different set of attributes. Example of the entity:

public class JsonEntity
{
   public String id;
   public String name;
   public String type;
   public String model;
}

JsonEntity is a part of the complex responses of different calls. The first call requires the whole JsonEntity without changes. Second call requires JsonEntity without type and model attributes. Thrid one requires JsonEntity without name attribute.

Is there any way to retrieve the same JSON entity with a particular set of attributes depending on the particular context (except separating JsonEntity ) using Jackson?

I see 3 ways of doing this:

1. Use @JsonGetter

This annotation tells jackson to use a metho rather than a field for serialization. Create 3 subclasses of JsonEntity , one for each response. Change JsonEntity and use @IgnoreField on every field, make them protected if possible. On each subclasses, create specific getter for the fields you need, example:

public class JsonEntitySecondCall extends JsonEntity
{
  @JsonGetter("id")
  public String getId(){
    return id;
  }

 @JsonGetter("name")
 public String getName(){
    return name;
  }
}

Also, create a clone/copy constructor for JsonEntity . For your second call, create a new JsonEntitySecondCall by cloning the original JsonEntity , and use it in your API. Because of the anotation, the created Object will only serialisze the given fields. I don't this you can just cast your object, because Jackson uses reflection.

2. Use @AnyGetter

the AnyGetter annotaiton allows you to define a map of what will be serialized:

private Map<String, Object> properties = new HashMap<>();

@JsonAnyGetter
public Map<String, Object> properties() {
    return properties;
}

Now you just need to tell your JsonEntity what properties it needs to return before each call (you could create 3 methods, one for each context, and use an enum to set which one must be used.).

3. Use @JsonInclude(Include.NON_NULL)

This annotation tells Jackson not to serialize a field if it is null. You can then clone your object and set null the fields you don't want to send. (this only works if you shouldn't send null elements to the API)

For more on Jackson annotations use this link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM