Jen
Jen

Reputation: 1338

Why can't Jackson deserialize this JSON?

I'm using Jackson to parse an ElasticSearch document into following data class

data class ElasticCity(
    val id: Long,
    val regionId: Long,
    val countryIso: String,
    val isFeatured: Boolean?
) {
    // For now Jackson does not support this for constructor parameters https://github.com/FasterXML/jackson-databind/issues/562
    @JsonAnySetter
    val names: MutableMap<String, String> = mutableMapOf()
}

However I'm getting following error (formatting mine)

com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException:
    Instantiation of [simple type, class net.goout.locations.model.ElasticCity] value failed
    for JSON property country_iso due to missing (therefore NULL) value for creator parameter countryIso which is a non-nullable type
    at [Source: (byte[])
        "{
            "name.cs":"Brno",
            "countryIso":"CZ",
            "regionId":85682423,
            "timezone":"Europe/Prague",
            "name.de":"Brünn",
            "name.sk":"Brno",
            "id":101748109,
            "isFeatured":true,
            "name.pl":"Brno",
            "name.en":"Brno"
        }";
    line: 1, column: 186] (through reference chain: net.goout.locations.model.ElasticCity["country_iso"])

Clearly the key countryIso is present in the JSON but for some reason Jackson complains a key country_iso is missing. Why? How can I fix this?

Upvotes: 1

Views: 3661

Answers (1)

QuickSilver
QuickSilver

Reputation: 4045

try adding

data class ElasticCity(
    val id: Long,
    val regionId: Long,
    @JsonProperty(value = "countryIso") val countryIso: String,
    val isFeatured: Boolean?
)

Jackson mapper implicitly converts non start caps characters _

If you want to fix this at multiple places then take a look at @JsonNaming(PropertyNamingStrategy.. https://www.programcreek.com/java-api-examples/?api=com.fasterxml.jackson.databind.PropertyNamingStrategy

Upvotes: 2

Related Questions