Home > Software design >  JSON key is missing (using @JsonComponent on Spring-boot with kotlin)
JSON key is missing (using @JsonComponent on Spring-boot with kotlin)

Time:10-05

Thanks reading this question.

this problem confused me. I created code that response JSON data like below.

@RestController
class JsonTestController {

    @GetMapping("jsonTest")
    fun jsonTest(): ResponseEntity<HaveBoolean> {
        val value = BooleanValue(true)
        return ResponseEntity.ok(HaveBoolean(value))
    }

    data class BooleanValue(val value: Boolean)

    data class HaveBoolean(
        val isAdmin: BooleanValue,
    )
}

and @JsonComponent is below.

@JsonComponent
class BooleanValueJson {

    class Serializer : JsonSerializer<JsonTestController.BooleanValue>() {
        override fun serialize(value: JsonTestController.BooleanValue, gen: JsonGenerator, serializers: SerializerProvider) {
            gen.writeBoolean(value.value)
        }
    }

    class Deserializer : JsonDeserializer<JsonTestController.BooleanValue>() {
        override fun deserialize(p: JsonParser, ctxt: DeserializationContext): JsonTestController.BooleanValue =
            JsonTestController.BooleanValue(p.valueAsBoolean)
    }
}

When I request localhost://8082/jsonTest, I got empty json ({}). but, I tried other variable name like hoge, mean coding like below.

    data class HaveBoolean(
        val hoge: BooleanValue,
    )

then, I request again, I can get correctly json ({"hoge": true}).

Can't I use isAdmin name on data class ?

Do you have any idea why this problem is happening?

thanks.

CodePudding user response:

This is a known issue with jackson in kotlin. Jackson basically tries to remove is from the name but kotlin data class implementation doesn't have a proper getter without "is" resulting in mismatch. You can add JsonProperty("isAdmin") to the variable and it should work.

data class HaveBoolean(
    @get:JsonProperty("isAdmin")
    val isAdmin: BooleanValue,
)
  • Related