Jackson JSON @JsonIgnore and @JsonIgnoreProperties Examples

This post is comming after Java Infinite recursion (StackOverflowError) Jackson solutions as I said there we can solve the problem in multiple ways. I consider this implementation is not the best for that case, to ingore properies, in my opinion it shoudl be used only if you want to exclude properties like excluding user password from JSON. Also any ignored property will be excluded from read as well, so be careful when using this.

1. @JsonIgnore 

download source code

public class User {
    private String name;
    @JsonIgnore
    private String password;

we put annotation @JsonIgnore on password, we wat this to be excluded form Serialization, 

            String user =  objectMapper.writeValueAsString(new User("username","strongpassword"));
            System.out.println(user);

the output :

{
  "name" : "username"
}

now we want this to read this into a Java Object , and to test what happens, for this I'll add the password to the string :

            String theUser = "{\n" +
                    "  \"name\" : \"username\",\n" +
                    "  \"password\" : \"strongpassword\"\n" +
                    "}";
            User userFromJSON = objectMapper.readValue(theUser, User.class);
            System.out.println(userFromJSON);
            // will produce :User{name='username', password='null'}

as you can see even the password is included in String it will be ingored.

2. @JsonIgnoreProperties

download sources

@JsonIgnoreProperties({"password"})
public class User {
    private String name;
    private String password;

the Jackson code remains unchaged , but i'll add a new property in JSON

            String theUser = "{\n" +
                    "  \"name\" : \"username\",\n" +
                    "  \"isNotAbug\" : \"isAnImprovement\",\n" +
                    "  \"password\" : \"strongpassword\"\n" +
                    "}";
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "isNotAbug" (class org.newtutorials.jackson.infinite.recursion.jsonignore.model.User), not marked as ignorable (one known property: "name"])
 at [Source: {
  "name" : "username",
  "isNotAbug" : "isAnImprovement",
  "password" : "strongpassword"
};

beacuse isNotAbug is present , we are not able to read this JSON, so we need to adapt the JsonIgnoreProperties to be able to read this:

@JsonIgnoreProperties(ignoreUnknown = true, value = {"password"})
public class User {
    private String name;
    private String password;

adding @JsonIgnoreProperties ignoreUnknown=true will solve our problem:

            User userFromJSON = objectMapper.readValue(theUser, User.class);
            System.out.println(userFromJSON);
//The output: User{name='username', password='null'}

 

Category: Java Tutorials