我的 Java 应用程序中有以下类:
@JsonIgnoreProperties(value = {"myProperty"}, allowSetters = true)
public class Test {
private String myProperty;
// getter and setter
}
我想用 ObjectMapper 将此对象转换为 json,但“myProperty”不转换,我想忽略该注释(@JsonIgnoreProperties),但请记住我仍想使用另一个注释。 在提出问题之前,我尝试修复它并分别为我的对象映射器定义一种自定义 Introspector 和 setAnnotationIntrospector 并对其进行测试,但问题未解决:
public class TestCustomIntrospector1 extends JacksonAnnotationIntrospector {
@Override
public PropertyName findNameForSerialization(Annotated a) {
if (a.getAnnotated().equals(JsonIgnoreProperties.class)) {
return null;
}
return super.findNameForSerialization(a);
}
}
public class TestMain {
public static void main(String[] args) {
Test obj = new Test();
obj.setMyProperty("this is for test");
try {
String json = new ObjectMapper()
.setAnnotationIntrospector(new TestCustomIntrospector1())
.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
System.out.println(json);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
另一个内省者:
public class TestCustomIntrospector2 extends JacksonAnnotationIntrospector {
@Override
public boolean isAnnotationBundle(Annotation ann) {
if (ann.annotationType() == JsonIgnoreProperties.class) {
return false;
}
return super.isAnnotationBundle(ann);
}
@Override
public boolean hasIgnoreMarker(AnnotatedMember m) {
JsonIgnoreProperties ignoreProperties = m.getAnnotation(JsonIgnoreProperties.class);
if (ignoreProperties != null) {
return ignoreProperties.ignoreUnknown();
}
return super.hasIgnoreMarker(m);
}
}
public class TestMain {
public static void main(String[] args) {
Test obj = new Test();
obj.setMyProperty("this is for test");
try {
String json = new ObjectMapper()
.setAnnotationIntrospector(new TestCustomIntrospector2())
.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
System.out.println(json);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
我想要以下结果:
{
"myProperty": "this is for test"
}
有人可以帮助我吗?
测试自定义内省器2:
public class TestCustomIntrospector2 extends JacksonAnnotationIntrospector {
@Override
public JsonIgnoreProperties.Value findPropertyIgnoralByName(MapperConfig<?> config, Annotated a){
return JsonIgnoreProperties.Value.empty();
}
}