Use JsonInclude annotation to ignore empty values ​​in extended class

Java 1.8, Jackson 2.1.5 Library

I need to override the behavior of how an object is serialized in json.

I need to ignore the property bonusfrom the json serialized response in case the value is null and the employee is employee Partner. However, trying to use the code below does not work properly.

class Employee{
    private String bonus;
    public String getBonus(){return bonus;}
    public String setBonus(){this.bonus = bonus;}
}

class Partner extends Employee{
    @Override
    @JsonInclude(NON_NULL)
    public String getBonus(){return super.getBonus();}
}

Any help?

+4
source share
1 answer

If you can do without exceptions to all properties null, you can use @JsonSerializein a class. The following test succeeds for me using Jackson 2.1.5:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.junit.Test;

public class SomeTest {
    public static class Employee {
        private String bonus;

        public String getBonus() {
            return bonus;
        }

        public void setBonus(String bonus) {
            this.bonus = bonus;
        }
    }

    @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
    public static class Partner extends Employee {
        @Override
        public String getBonus() {
            return super.getBonus();
        }
    }

    @Test
    public void testSerialize() throws Exception {
        Employee employee = new Employee();
        Partner partner = new Partner();

        ObjectMapper objectMapper = new ObjectMapper();
        System.out.println("Employee: " + objectMapper.writeValueAsString(employee));
        System.out.println(" Partner: " + objectMapper.writeValueAsString(partner));
    }
}

Output:

Employee: {"bonus":null}
 Partner: {}
+2

Source: https://habr.com/ru/post/1614153/


All Articles