标签: annotation-introspector

如何使用 Jackson AnnotationIntrospector 有条件地忽略属性

我想创建一个注释,让 Jackson 忽略带注释的字段,除非设置了某个跟踪级别:

public class A {
    @IgnoreLevel("Debug") String str1;
    @IgnoreLevel("Info") String str2;
}
Run Code Online (Sandbox Code Playgroud)

或者,如果这更容易实现,我也可以为不同级别分别添加注释:

public class A {
    @Debug String str1;
    @Info String str2;
}
Run Code Online (Sandbox Code Playgroud)

根据 的配置ObjectMapper,要么

  • 序列化和反序列化时,应忽略所有“调试”和“信息”字段,或
  • 应忽略所有“调试”字段,或
  • 所有字段都应序列化/反序列化。

我想这应该可以通过自定义AnnotationIntrospector. 我有这篇文章,但它没有显示如何实现自定义AnnotationIntrospector.

java json annotations jackson annotation-introspector

5
推荐指数
1
解决办法
4179
查看次数

根据 Java 环境变量中的值创建使用 @JsonIgnore 的自定义注释

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

public class Vehicle {
    String vehicle_name;
    String vehicle_model;
    //getters and setters  
    @MyAnnotation
    public String getVehicle_model() {
        return vehicle_model;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@JsonIgnore
public @interface MyAnnotation {
}
Run Code Online (Sandbox Code Playgroud)

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

提前致谢。

编辑:我的尝试JacksonAnnotationIntrospector

public class MyAnnotationIntrospector extends JacksonAnnotationIntrospector {
@Override
public boolean hasIgnoreMarker(AnnotatedMember annotatedMember) {
    //need this part
   }
 }
Run Code Online (Sandbox Code Playgroud)

的实现ObjectMapper

 ObjectMapper mapper = new ObjectMapper();
 String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this);
Run Code Online (Sandbox Code Playgroud)

java json jackson annotation-introspector java-annotations

4
推荐指数
1
解决办法
2434
查看次数