Quarkus Panache MongoDB:将 ObjectId 序列化为字符串

Quarkus Panache MongoDB: Serialize ObjectId as String

我正在按照教程 https://quarkus.io/guides/rest-data-panache and https://quarkus.io/guides/mongodb-panache 使用 Quarkus Panache MongoDB.

实现一个简单的 MongoDB 实体和资源

这是我目前的情况:

@MongoEntity(collection = "guests")
class GuestEntity(
    var id: ObjectId? = null,
    var name: String? = null
)

@ApplicationScoped
class GuestRepository: PanacheMongoRepository<GuestEntity>

interface GuestResource: PanacheMongoRepositoryResource<GuestRepository, GuestEntity, ObjectId>

当运行这个时候,我可以通过调用

来创建文档
POST localhost:8080/guest
Content-Type: application/json

{
  "name": "Foo"
}

响应包含创建的实体

{
  "id": {
    "timestamp": 1618306409,
    "date": 1618306409000
  },
  "name": "Foo"
}

注意,id 字段是一个对象,而我希望它是一个字符串。

要将 id 字段序列化为字符串,请将以下注释应用于 id 字段

import com.fasterxml.jackson.databind.annotation.JsonSerialize
import io.quarkus.mongodb.panache.jackson.ObjectIdSerializer

@MongoEntity(collection = "guests")
class GuestEntity(
    // important: apply the annotation to the field
    @field:JsonSerialize(using = ObjectIdSerializer::class)
    var id: ObjectId? = null,
    var name: String
)

现在的响应是

{
  "id": "607567590ced4472ce95be23",
  "name": "Foo"
}

原来应用程序使用的是 quarkus-resteasy 而不是 quarkus-resteasy-jackson

一旦适当的依赖关系到位,一切都按预期工作