kotlinktorktorm

Serializing entities and sending response gives the entity property name instead of the column name


I'm trying to understand how to get certain entities through the database and get the column names instead of the property names of the entity and serialize them and send the response.

get("/v1/posts") {
        val posts= service.getAll()

        val mapper: ObjectMapper = JsonMapper.builder()
            .addModule(JavaTimeModule())
            .addModule(KtormModule())
            .build()

        val json = mapper.writeValueAsString(posts)
        call.respond(HttpStatusCode.OK, json)
}

This is what I'm currently doing in my get request. But it gives me output like this:

{
    "id": 1,
    "title": "Some Title",
    "description": "some text...",
    "createdAt": [
        2018,
        9,
        16,
        1,
        1,
        36,
        399357000
    ]
}

My entity looks like this:

interface Post: Entity<Post> {
    companion object : Entity.Factory<Post>()
    val id: Int
    var title: String
    var description: String
    var createdAt: LocalDateTime
}

object Posts: Table<Post>("posts") {
    val id = int("id").primaryKey().bindTo { it.id }
    val title = varchar("title").bindTo { it.title }
    val description = varchar("description").bindTo { it.description }
    val createdAt = datetime("created_at").bindTo { it.createdAt }
}

val Database.posts get() = this.sequenceOf(Posts)

Edit. This is in my Application.kt file:

fun Application.module() {
    install(ContentNegotiation) {
        json()
        jackson {
            configure(SerializationFeature.INDENT_OUTPUT, true)
            setDefaultPrettyPrinter(DefaultPrettyPrinter().apply {
                indentArraysWith(DefaultPrettyPrinter.FixedSpaceIndenter.instance)
                indentObjectsWith(DefaultIndenter("  ", "\n"))
            })
            registerModule(JavaTimeModule())  // support java.time.* types
            configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
        }
    }

    configureRouting()
}

How can I make createdAt be created_at in the JSON response?


Solution

  • Seems like you are using Jackson as your serialization engine. If so there are two ways

    1. Annotate the particular field with @JsonProperty("created_at") see https://www.baeldung.com/jackson-annotations#1-jsonproperty
    2. Annotate the class with @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class) - "Snake Case" is a style of naming that puts underscores instead of Initial Capitals which is the Kotlin standard. This applies to the whole entity. See https://www.baeldung.com/jackson-deserialize-snake-to-camel-case