Jackson将JSON数组序列化为String属性

时间:2019-06-19 02:17:07

标签: json jackson json-deserialization

我正在尝试使用Jackson来从远程Web服务中获取有效载荷,其中返回的JSON有时包含被定义为Arrays,有时则定义为纯字符串的属性。

我尝试使用JsonRawValue注释字段,但仍然出现错误:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.lang.String out of START_ARRAY token

以下Kotlin类用于序列化所述JSON有效负载:

data class Device(
    @get:JsonProperty("common.uuid")
    val commonUuid: String? = null,

    @field:JsonRawValue
    @get:JsonProperty("user.ldap.groups.dn")
    val userLdapGroupsDn: String? = null
)

data class DeviceSearchResults(
    @JsonProperty("resultCount")
    val resultCount: Int = 0,

    @JsonProperty("totalCount")
    val totalCount: Int = 0,

    @JsonProperty("results")
    val results: List<Device> = listOf()
)

..和我进行了以下单元测试以显示错误:

stubs-get-devices.json

{
  "results": [
    {
      "common.uuid": "848ba0e8-d313-4df5-9a9e-3d9ea28951fa",
      "user.ldap.groups.dn": [
        "cn=qss-role-megamall-internet,ou=foo,ou=groups,dc=bar"
      ]
    }
  ]
}
@Test
fun testJsonSerialization() {
    val objectMapper = ObjectMapper().apply {
        setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
        configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        registerModule(KotlinModule())
    }
    val file = File("stubs/get-devices.json")
    val value = objectMapper.readValue(file, DeviceSearchResults::class.java)
    assertThat(value).isNotNull
    println(value)
}

是否有一种方法可以将JSON数组值强制转换为序列化对象中的String属性?

0 个答案:

没有答案