spring-bootkotlinspring-kotlin

How to dynamically add key value pairs in Kotlin object?


I have Spring Boot REST api which returns JSON object like this -

{
  "id": "1"
  "timestamp": "2020-08-03T08:49:02.679+00:00"
  "message": "hello"
}

This is directly derived from @Entity like this -

fun getMessage(id: Long) = messageRepository.findById(id)

Here, Spring boot automatically converts the response into JSON. However, I want to add another key-value pair in the getMessage() function. Similar to this - How can I add a key/value pair to a JavaScript object? but in Java/ Kotlin.

How do I do that?


Solution

  • Maybe you could create another Model for that and create an extension to convert into the new model.

    data class Message(
        val id: Int,
        val timestamp: String, 
        val message: String   
    )
    
    data class MessageWithMoreInfo(
        val id: Int,
        val timestamp: String, 
        val message: String,
        val info: String   
    )
    
    fun Message.toMessageWithMoreInfo(val info: String) = MessageWithMoreInfo(
        id,
        timestamp,
        message,
        info
    )