Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin data class to JSON with spring/jackson

I'm tryin to expose some data class as JSON objects but something ain't working.

I have the following data classes:

data class Link(
        @JsonProperty("rel")
        @JsonView(View.Bind::class)
        val rel: String,

        @JsonProperty("method")
        @JsonView(View.Bind::class)
        val method: HttpMethod,

        @JsonProperty("href")
        @JsonView(View.Bind::class)
        val href: String)


data class MetaData(val status: HttpStatus) {
    @JsonView(View.Bind::class)
    @JsonProperty("status_code")
    fun getStatusCode(): Int {
        return status.value()
    }

    @JsonView(View.Bind::class)
    @JsonProperty("status_desc")
    fun getStatusDesc(): String {
        return status.name
    }
}

data class Payload(
        @JsonView(View.Bind::class)
        @JsonProperty("payload")
        val payload: Any,

        @JsonProperty("_meta")
        @JsonView(View.Bind::class)
        val metaData: MetaData,

        @JsonProperty("_links")
        @JsonView(View.Bind::class)
        val links: List<Link>)

And for some reason, when the Payload class is a JAVA class everything works fine, but when it is a kotlin class only the payload element gets into the JSON.

For dependency i'm using:

<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-stdlib</artifactId>
    <version>1.0.1-1</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-kotlin</artifactId>
    <version>2.7.1-2</version>
</dependency>

If i change the "_meta" and "_links" to "meta" and "links" the "links" elements are rendered.

like image 969
Bruno Araujo Avatar asked Mar 29 '16 19:03

Bruno Araujo


1 Answers

Based on the information you gave, the problem seems to be with using _ as JsonProperty value. You may have observed all your properties for MetaData contain _. Try removing all the underscores and see. I hope also you've registered the ObjectMapper, example in your Application class:

@Bean
open fun objectMapperBuilder(): Jackson2ObjectMapperBuilder
        = Jackson2ObjectMapperBuilder().modulesToInstall(KotlinModule())
like image 80
zulqarnain Avatar answered Oct 09 '22 03:10

zulqarnain