3

我需要创建一个新注释,用于在环境变量var == false. 我尝试使用JsonAnnotationIntrospector,但无法获得预期的输出。

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

这里我需要删除vehicle_model环境变量时的属性var == false

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

这是我的自定义注释的声明。有人可以告诉我应该如何编写 Introspector 部分来获得我需要的功能吗?

提前致谢。

编辑:我的尝试JacksonAnnotationIntrospector

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

的实现ObjectMapper

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

1 回答 1

4

像这样

@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);
    }
}
于 2018-09-12T15:16:51.047 回答