Tutorial

Using @JsonIgnore or @JsonProperty to hide sensitive data in JSON response


Using @JsonIgnore or @JsonProperty to hide sensitive data in JSON response

If you are working with Java and happen to use Spring Boot or Jackson Serializer , which Spring Boot use by default. You must have encountered this problem once at least.

Suppose you have User Object which contain password property .

public class User {
    private String username;
    private String password;
}

If you return this response from a service method like below

@GetMapping("/user/{id}")
public User getUser(String id){
    return new User();
}

You will get service response as

{
 "user_name" : "Bob",
 "password"  : "secret_password"
}

May be that’s not what you want exactly. You might not want to expose password of a user to the consumer of your service.

But solution is just a annotation away. You can block the password property for external exposure by adding @JsonIgnore on the password property.

public class User {
    private String username;
    
    @JsonIgnore
    private String password;
}

Now if get the response from the service. You would not get password property in the serialized response.

{
 "user_name" : "Bob"
}

So far so good!!

But unfortunately , now if you want to use the same User object for the signup service, You would not be able to do that because setting or unmarshaling of password property is blocked as well.

Thus, May be you might only like to block the marshaling ( getting ) of sensitive property but not the unmarshalling( setting ) of that.

For this you can add @JsonIgnore only to getter of the property and not to the property itself.

public class User {
    private String username;
    
    
    private String password;

    @JsonIgnore
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Now password property would not be available in the response but could be used to set the password.

Thats it!! Simple right?

But there is more..

Since version 2.6: a more intuitive way is to use the com.fasterxml.jackson.annotation.JsonProperty annotation on the field. You can use appropriate access value as per your use case.

public class User {
    private String username;

    @JsonProperty(access = Access.WRITE_ONLY)
    private String password;

}

Even if a getter exists, the field value is excluded from serialization.

comments powered by Disqus