Jsonオブジェクトの特定の属性をカスタムのIgnoreアノテーションに基づいて無視する必要があります。これは特定のオブジェクトマッパーにのみ必要です。しかし、他のケースでは、JsonPropertyアノテーションが必要です。私はJacksonAnnotationInstrospectorを使ってこれを行っています。しかし私がそうするとき、注釈のどちらも認められません。例えば@JsonIgnoreと@JsonPropertyが同じ属性にある
、私は私の出力は、このようなことがしたい:
通常のオブジェクトマッパー:JacksonAnnotationInstrospectorでオブジェクトマッパーを使用して{"element3":"C","element_1":"A","element_2":"B"}
予想される出力:私は実際にJacksonAnnotationInstrospectorを取得しています{"element_1":"A"}
出力: {"element2":"B","element_1":"A"}
以下は私のコードです:
public class TestClass {
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setAnnotationIntrospector(new JsonIgnoreIntrospector());
MockObject mockObject = new MockObject("A", "B", "C");
String string = objectMapper.writeValueAsString(mockObject);
System.out.println(string);
}
public static class MockObject {
@JsonProperty("element_1")
String element1;
@CustomJsonIgnore
@JsonProperty("element_2")
String element2;
@CustomJsonIgnore
String element3;
public MockObject(String element1, String element2, String element3) {
this.element1 = element1;
this.element2 = element2;
this.element3 = element3;
}
public String getElement1() {
return element1;
}
public void setElement1(String element1) {
this.element1 = element1;
}
public String getElement2() {
return element2;
}
public void setElement2(String element2) {
this.element2 = element2;
}
public String getElement3() {
return element3;
}
public void setElement3(String element3) {
this.element3 = element3;
}
}
public static class JsonIgnoreIntrospector extends JacksonAnnotationIntrospector {
@Override
public boolean hasIgnoreMarker(final AnnotatedMember m) {
return m.hasAnnotation(CustomJsonIgnore.class) || m.hasAnnotation(JsonIgnore.class);
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.CONSTRUCTOR})
@JacksonAnnotation
public @interface CustomJsonIgnore {
}
}