如何使用Kotlin在Jackson中使用默认值和必需值控制空反序列化?

时间:2018-10-03 13:17:29

标签: kotlin jackson

使用Jackson 2.9.6

我有以下数据类定义:

data class SomeDTO @JsonCreator internal constructor
(
    @get:JsonProperty(value = "first-property", required = true)
    @param:JsonProperty(value = "first-property", required = true)
    val firstProperty: Long?,

    @get:JsonProperty(value = "second-property")
    @param:JsonProperty(value = "second-property")
    val secondProperty: Int = 1234

    @get:JsonProperty("third-property", required = true)
    @param:JsonProperty("third-property", required = true)
    val thirdProperty: Int
)

我期望反序列化为SomeDTO的JSON

  1. 如果缺少firstProperty,它将引发异常。
  2. 如果firstProperty为null,则应分配null,因为它可以为null。
  3. 如果secondProperty缺失或为空,则应分配默认值1234
  4. 如果thirdProperty丢失或为空,则应引发异常。

基本上,我可以控制哪些值可以反序列化以及转换为什么。

我正在遇到的事情:

如果 not 使用KotlinModule,则(1),(2)和(4)可以工作,但(3)失败,并显示:

  

com.fasterxml.jackson.databind.exc.MismatchedInputException:无法将null映射为int类型(将DeserializationConfig.DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES设置为'false'以允许)

如果使用KotlinModule,则(2),(3)和(4)起作用,但(1)失败。

ObjectMapper配置的主要部分:

disable(
        MapperFeature.AUTO_DETECT_CREATORS,
        MapperFeature.AUTO_DETECT_FIELDS,
        MapperFeature.AUTO_DETECT_GETTERS,
        MapperFeature.AUTO_DETECT_IS_GETTERS
       )
disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)

registerModule(ParanamerModule())
registerModule(KotlinModule()) // Might be registered or not

disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)

我认为使用KotlinModule会更容易,但是我不知道如何在JSON中缺少该属性时不告诉它不将空值自动分配给可空字段

2 个答案:

答案 0 :(得分:1)

这应该做您想要的:

data class SomeDTO(
        @JsonProperty(value = "first-property", required = true)
        val firstProperty: Long?,

        @JsonProperty(value = "second-property")
        val secondProperty: Int = 1234,

        @JsonProperty("third-property", required = true)
        val thirdProperty: Int
)

一些注意事项:

1。 由于您在注释字段中使用了主要的构造函数,因此在Kotlin中,您不需要@JsonCreator注释。

这是GitHub page of the Jackson project所说的:

  

默认情况下,Jackson尝试使用“默认”构造函数(   创建值实例时不接受任何参数)。但是你也可以   选择使用其他构造函数或静态工厂方法   创建实例。为此,您将需要使用注释   @JsonCreator,可能还有@JsonProperty批注将名称绑定到   争论

  1. 您不需要单独的@get@param注释。仅@JsonProperty就足以满足您的用例。

答案 1 :(得分:1)

缺少firstProperty时,将Kotlin模块更新到版本2.9.7会产生异常。我已经反复测试过,在2.9.6和2.9.7之间来回测试,并从OP复制了代码和配置。

2.9.7中的错误修复与OP中描述的意外行为匹配。

  

修复#168,其中JsonProperty(required=true)被无效性检查忽略并覆盖了

https://github.com/FasterXML/jackson-module-kotlin/issues/168