0

我正在按照教程https://quarkus.io/guides/rest-data-panachehttps://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字段如何是一个对象,而我希望它是一个字符串。

4

2 回答 2

2

事实证明,该应用程序使用quarkus-resteasy的是quarkus-resteasy-jackson.

一旦建立了适当的依赖关系,一切都按预期工作

于 2021-04-14T08:36:22.303 回答
0

要将字段序列化为字符串,请对字段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"
}
于 2021-04-13T09:43:53.403 回答