Home > Mobile >  Jackson: How to only ignore a Json property when creating a response?
Jackson: How to only ignore a Json property when creating a response?

Time:11-21

I my Spring app I am getting a String from S3, I need convert this to JSON then to Person object. This is all working as expected.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

        ObjectMapper mapper = new ObjectMapper();
        JsonNode actualObj = mapper.readTree(s );
        Person person = mapper.treeToValue(actualObj, Person.class);

        if(person.getBalance()>0{
           person.setInCredit(true);
        }
      
       // todo - how to not return balance?

My Object is as follows:

import com.fasterxml.jackson.annotation.JsonProperty;
    
    public class Person{
    
      @JsonProperty("id")
      private Integer id;
    
      @JsonIgnore
      @JsonProperty("balance")
      private Integer balance;
    
      @JsonProperty("inCredit")
      private Boolean inCredit;
    
      // other fields and setters etc
    
    }

As can be seen above, I need to read balance initially to determine the inCredit field, however I want to exclude the balance from the json response.

How can I ensure that the field balance is read ok from my query but is not returned again in my response from my endpoint?

Note - I tried adding JsonIgnore but this did not work.

CodePudding user response:

You can use code as below:

@JsonProperty(access = JsonProperty.Access.WRITE_ONLY, value = "balance")
private Integer balance;

Or you can add @JsonIgnore only on getter method.

  • Related