How can I have different names for the same field in different APIs?—Jackson

Viewed 89

I have an API whose response is as follows:

{
  ruleId:”123”,
  ruleName:”Rule1”
}

Now I am introducing a new Api which exactly has these fields but the response should not have name as ruleId ,ruleName but as id,name:

{
  id:”123”,
  name:”Rule1”
}

I should change in such a way so that the previous Api response should not be impacted. Thought to use JsonProperty /JsonGetter but it will change the previous Api response as well.

Is there any way that I can have 2 getters for the same field and then use one getter for previous Apis and other one for my purpose? (My concern is only when converting Pojo to JSON)

Can anyone help?

1 Answers

Since you want serialize the object differently in different cases, using jackson mix-in is preferred.

Here is example how to do that.

If your pojo looks something like this:

public class CustomPojo {


    private String ruleId;


    private String ruleName;


    public String getRuleId() {
        return ruleId;
    }


    public void setRuleId(String ruleId) {
        this.ruleId = ruleId;
    }


    public String getRuleName() {
        return ruleName;
    }

    public void setRuleName(String ruleName) {
        this.ruleName = ruleName;
    }
}

First, you need to create one interface (or class) like this:

import com.fasterxml.jackson.annotation.JsonProperty;

public interface CostomPojoMixin {

    @JsonProperty("Id")
    String getRuleId();

    @JsonProperty("name")
    String getRuleName();
}

This interface will be used to rename fields ruleId and ruleName during serilization.

Then when you have all this setup you can write controller method and customize ObjectMapper:

 @GetMapping(value = "/test/mixin")
        public String testMixin() throwsJsonProcessingException {
            CostomPojo cp = new CostomPojo();
            cp.setRuleId("rule");
            cp.setRuleName("name");
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.addMixIn(CustomPojo.class, CostomPojoMixin.class);
            String json = objectMapper.writeValueAsString(cp);
            return json;
    
        }

This endpoint should return response like this:

{"Id":"rule","name":"name"}
Related