skip to Main Content

When I’m trying to deserialize code below

import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper

fun main() {
    val objectMapper = jacksonObjectMapper()

    val jsonString = "{" +
            ""v_string1": "some_string1", " +
            ""v_string2": "some_string2", " +
            ""v_string3": "some_string3", " +
            ""v_string4": "some_string4"" +
            "}"

    val result = objectMapper.readValue(jsonString, TestProps::class.java)
    println(result)
}

data class TestProps (

    @JsonProperty("v_string1")
    val vString1: String? = null,

    @field:JsonProperty("v_string2")
    val vString2: String? = null,

    @get:JsonProperty("v_string3")
    val vvString3: String? = null,

    @get:JsonProperty("v_string4")
    val vString4: String? = null,
)

I’m receiving exception:

Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "v_string4" (class auto.atom.TestProps), not marked as ignorable (4 known properties: "v_string2", "v_string3", "vString4", "v_string1"])

It’s failing only with @get:JsonProperty and when property name does not follow the convention (second letter is capital).
But I can’t change the annotation or field name because of using the open api generator plugin, it generates classes with @get:JsonProperty. I didn’t find the configuration to change annotation or fieldName.

My gradle file:

plugins {
    kotlin("jvm") version "2.0.10"
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.18.1")
}

I’ve tried to dump jackson version for openapi-generator-gradle-plugin, but it still generating fields with @get:JsonProperty

2

Answers


  1. Chosen as BEST ANSWER

    Adding the PropertyNamingStrategies.SNAKE_CASE and specifying com.fasterxml.jackson.core:jackson-databind in classpath with bumped version helped.

    val mapper = JsonMapper()
        .setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)
        .registerKotlinModule()
    

  2. I would just configure the object mapper to not be case insensitive for properties.
    You can see how to do that the jackson api docs:

    Or refer to this question with various ways of configuring Jackson for this based on the version of Jackson you’re using:
    Case insensitive JSON to POJO mapping without changing the POJO

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search