Create custom annotation that uses @JsonIgnore based on value in environment variable in Java

Viewed 1576

I need to create a new annotation which is used to ignore a field in the output JSON file when the environment variable var == false. I tried to use JsonAnnotationIntrospector, but could not get the expected output.

public class Vehicle {
    String vehicle_name;
    String vehicle_model;
    //getters and setters  
    @MyAnnotation
    public String getVehicle_model() {
        return vehicle_model;
    }
}

Here I need to remove vehicle_model attribute when the environmental variable var == false.

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@JsonIgnore
public @interface MyAnnotation {
}

This is the declaration of my custom Annotation. Can Someone tell me how should I write the Introspector part to get the functionality I need?

Thanks in advance.

Edit: My attempt at JacksonAnnotationIntrospector

public class MyAnnotationIntrospector extends JacksonAnnotationIntrospector {
@Override
public boolean hasIgnoreMarker(AnnotatedMember annotatedMember) {
    //need this part
   }
 }

And the implementation of ObjectMapper is

 ObjectMapper mapper = new ObjectMapper();
 String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this);
1 Answers

like this

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface MyAnnotation {
}

public class Vehicle {

    private String vehicle_name;

    @MyAnnotation
    private String vehicle_model;
    //getters and setters

    public static void main(String[] args) throws JsonProcessingException {

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {

            @Override
            public boolean hasIgnoreMarker(AnnotatedMember m) {

                if (!System.getenv("var").equals("true")) {
                    return false;
                }
                if(_findAnnotation(m, MyAnnotation.class) != null){
                    return true;
                } else {
                    return false;
                }
            });

        Vehicle vehicle = new Vehicle();
        vehicle.setVehicle_model("vehicle_model_value");
        vehicle.setVehicle_name("vehicle_name_value");

        String value = objectMapper.writeValueAsString(vehicle);
        System.out.println(value);
    }
}
Related