Json子类型上的Json Ignore属性

Json子类型上的Json Ignore属性,json,jackson,Json,Jackson,我有一个Scala case类,它表示我的JSON,如下所示: class MyJSON(x: Int, typeA: TypeA, typeB: TypeB) @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes(Array( new Type(value = classOf[ClassA], name = "ClassA

我有一个Scala case类,它表示我的JSON,如下所示:

class MyJSON(x: Int, typeA: TypeA, typeB: TypeB)

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes(Array(
  new Type(value = classOf[ClassA], name = "ClassA"),
  new Type(value = classOf[ClassB], name = "ClassB")))
trait TypeA {
...
...
}
@JsonIgnoreProperties(ignoreUnknown=true)
class MyJSON(x: Int, typeA: TypeA, typeB: TypeB)
在我的ClassA中,我有一些从JSON反序列化的字段。但我也希望,如果某些字段不是我的类对象的一部分,我希望它们被忽略。我所做的是在MyJSON类上使用@JsonIgnoreProperties(ignoreUnknown=true)注释,如下所示:

class MyJSON(x: Int, typeA: TypeA, typeB: TypeB)

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes(Array(
  new Type(value = classOf[ClassA], name = "ClassA"),
  new Type(value = classOf[ClassB], name = "ClassB")))
trait TypeA {
...
...
}
@JsonIgnoreProperties(ignoreUnknown=true)
class MyJSON(x: Int, typeA: TypeA, typeB: TypeB)

当我的输入JSON有一些未知字段时,它失败了。但在我的例子中,当我将这个注释移动到我的一个类(比如ClassA)时,它被忽略了。问题是,我不想将这个ignore-properties注释添加到我的所有类中,而是将它添加到顶部,并希望它传播到所有类型。

我找到了一个非常优雅的解决方案。我使用jacksonmixin机制在运行时向目标类型添加额外的注释。以下是我所做的:

@JsonIgnoreProperties({ Array("field1", "field2") })
abstract class MixInAnnotations{}
在创建ObjectMapper的JSONMarshaller类中,我执行以下操作:

  val mapper = new ObjectMapper()
  mapper.registerModule(new MyApplicationModule)
MyApplicationModule现在看起来像:

public class MyApplicationModule extends com.fasterxml.jackson.databind.module.SimpleModule {

  public MyApplicationModule() {
    super(MyApplicationModule.class.getSimpleName());

    // Add the corresponding MixIn Annotations to ignore the JSON properties
    setMixInAnnotation(MyTargetClass1.class, MixInAnnotations.class);
    setMixInAnnotation(MyTargetTrait.class, MixInAnnotations.class);

  }
}
我调用setter方法将mixin符号添加到目标类中。这里的目标类也可能是具有JsonSubTypes注释的特性。因此,实际上,@JsonIgnoreProperties注释并没有污染我的所有类型。

试试这个

objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);