You won't be able to replicate javascript's way of injecting keys & values into objects, as Java (and Kotlin) is a statically typed language.
Spring's conversion to Json isn't magic. Most likely it will serialize your Entity with an Object Mapper (Jackson or Gson).
Now, you can work around this limitation in many ways (some are better than others), Luciano's answer being one of the best ones.
But, depending on what you are injecting into your entity and how your project design is defined, you could do exactly what javascript does by using the Object Mapper provided by the spring context and convert your Entity into a Map<String, Any>:
@Service
class AServiceImpl(
private val repository: ARepository,
// autowires the objectMapper
private val objectMapper: ObjectMapper
) : AService {
override fun getMessage(id: Long): Map<String, Any>{
val entity = repository.findById(id)
// here you have something more like a javascript Object
val map: MutableMap<String, Any> = objectMapper.convertValue(entity)
// so you can add key/value pairs to it
map["something"] = "some_value"
// but you will need to change the method signature
return map
}
}
Remember: passing maps is kinda dangerous, you lose many of the benefits Java/Kotlin brings :)