'Return by default toString() _id mongo spring boot kotlin

Hi im newer with Kotling, im working in into REST service using mongoDB as database im trying to get a info from database and its works but _id is showing as object not as string

Response

[
    {
        "id": {
            "timestamp": 1622599648,
            "date": "2021-06-02T02:07:28.000+00:00"
        },
        "name": "test",
        "description": "test",
        "createdDate": "2021-06-01T21:07:28.385",
        "modifiedDate": "2021-06-01T21:07:28.385"
    },
    {
        "id": {
            "timestamp": 1622600161,
            "date": "2021-06-02T02:16:01.000+00:00"
        },
        "name": "test",
        "description": "test",
        "createdDate": "2021-06-01T21:16:01.669",
        "modifiedDate": "2021-06-01T21:16:01.669"
    }
]

Class:

@Document
data class Patient (
        @Id
        
        val id: ObjectId = ObjectId.get(),
        val name: String,
        val description: String,
        val createdDate: LocalDateTime = LocalDateTime.now(),
        val modifiedDate: LocalDateTime = LocalDateTime.now()
        )

interface PatientRepository : MongoRepository<Patient, String> {
        fun findOneById(id: ObjectId): Patient
        override fun deleteAll()
}

What i can do to transform id to string? when i retrieve data?



Solution 1:[1]

You need cast your ObjectId To string with a bean using a serializer

@Bean
    fun customizer(): Jackson2ObjectMapperBuilderCustomizer? {
        return Jackson2ObjectMapperBuilderCustomizer { builder: Jackson2ObjectMapperBuilder -> builder.serializerByType(ObjectId::class.java, ToStringSerializer()) }
    }

And the respond:

[
    {
        "id": "60b6e7e03c52e16a1a1b000c",
        "name": "test",
        "description": "test",
        "createdDate": "2021-06-01T21:07:28.385",
        "modifiedDate": "2021-06-01T21:07:28.385"
    },
    {
        "id": "60b6e9e11194486befd09e8c",
        "name": "test",
        "description": "test",
        "createdDate": "2021-06-01T21:16:01.669",
        "modifiedDate": "2021-06-01T21:16:01.669"
    }
]

Solution 2:[2]

varman has already mentioned on his comment.

what about changing id type to String like below?

@Document
data class Patient (
        @Id
        
        val id: ObjectId = ObjectId.get(),
        val name: String,
        val description: String,
        val createdDate: LocalDateTime = LocalDateTime.now(),
        val modifiedDate: LocalDateTime = LocalDateTime.now()
)
@Document
data class Patient (
        @Id
        
        val id: String = ObjectId.get().toString(),
        val name: String,
        val description: String,
        val createdDate: LocalDateTime = LocalDateTime.now(),
        val modifiedDate: LocalDateTime = LocalDateTime.now()
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel ORTIZ
Solution 2 Jayground