Jackson Serialize JSON array as String property

Viewed 658

I am trying to ingest payloads from a remote web service using Jackson where the returned JSON contains properties that are defined as Arrays sometimes and plain Strings at other times.

I tried annotating the field using JsonRawValue but I am still getting the error:

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

The following Kotlin classes are used to serialize the said JSON payload:

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()
)

.. and I put together the following unit test to show the error:

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)
}

Is there a way to coerce a JSON array value into a String property within the serialized Object?

0 Answers
Related