如何在字段级别上忽略未知字段?

4
我正在请求中使用来自另一个模块的类。
public class KeyInput {
  @NotNull
  private Long id;
  @NotNull
  private String startValue;
  @NotNull
  private String endValue;
}

由于模块不包含jackson库,我无法在此类上放置@JsonIgnoreProperties(ignoreUnknown = true)注释。

将其放置在请求类中使用的字段级别上并没有成功。

@JsonIgnoreProperties(ignoreUnknown = true)
private List<KeyInput> keys;

以下是传入的请求。请注意问题的来源,即两个字段(nametype),它们在 KeyInput 类中未声明。

{
    "id": 166,
    "name": "inceptionDate",
    "type": "DATE",
    "startValue": "22",
    "endValue": "24"
}

如果这个类不在我的包中,我该如何告诉Jackson忽略未知字段?

P.S: 我知道我可以将键作为JSON字符串获取,并使用ObjectMapper进行序列化(通过将配置DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES设置为false),但我在这里寻找一种更清晰的解决方案。

另外,在我的类中放置这些字段并从未使用它们是另一种不好的解决方案。


2个回答

2

我能想到两种方法。

方法一

创建一个空的子类,继承自 KeyInput 类。这是最简单的方法。

@JsonIgnoreProperties(ignoreUnknown = true)
public class InheritedKeyInput extends KeyInput{}

方法二

KeyInput类创建一个自定义的反序列化器。

public class KeyInputDeserializer extends JsonDeserializer<KeyInput> {

    @Override
    public KeyInput deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        JsonNode node = jsonParser.getCodec().readTree(jsonParser);
        KeyInput keyInput = new KeyInput();
        keyInput.setId(node.get("id").asLong());
        keyInput.setEndValue(node.get("startValue").textValue());
        keyInput.setStartValue(node.get("startValue").textValue());
        return keyInput;
    }
}

使用配置类将此反序列化程序绑定到KeyInput

@Configuration
public class JacksonConfig implements Jackson2ObjectMapperBuilderCustomizer {

    @Override
    public void customize(Jackson2ObjectMapperBuilder builder) {
        builder.failOnEmptyBeans(false)
                .deserializerByType(KeyInput.class, new KeyInputDeserializer());
    }
}

0

只需在你想忽略的字段上方添加一个简单的附加项 @JsonIgnore


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接