【问题标题】:ReactiveMongo with Play-json responsibility's divisionReactiveMongo 与 Play-json 职责的划分
【发布时间】:2020-11-16 14:24:33
【问题描述】:

我正在使用 play-json 将传入的 json 序列化为案例类,例如来自 sqs 源或来自 api 调用。

它是一个非常简单的 JsonSerialization 类,我在需要的地方导入它:

object JsonSerialization {
  implicit val StatusFormat: Format[Status] = EnumFormats.formats(Status)
  implicit val PersonFormat: OFormat[Person] = Json.format[Person]
}

但现在我想知道,根据我对 Dao 的理解,需要将我的案例类序列化为 BSON ,因为我的 Dao 获取了案例类,并且当我从某些东西中获取反序列化到我的案例类时.我只在Dao中导入:

import reactivemongo.play.json.compat.json2bson.{toDocumentReader, toDocumentWriter}
import serializers.JsonSerialization._

查找和插入效果很好,

  def insert(person: Person): Future[Person] = {
    val writeRes: Future[WriteResult] = collection.insert.one(person)

    writeRes.onComplete {
      case Failure(e) => e.printStackTrace()
      case Success(writeResult) =>
        logger.info(s"successfully inserted person")
    }

    writeRes map { _ => person }
  }


  def find(name: String): Future[Person] = {
    collection.find(BSONDocument(
      "name" -> name
    )).requireOne[Person]
  }

你能告诉我道中哪个部分负责什么吗?我有点迷茫

对不起,如果这是一个初学者问题,但得到简短的解释会有所帮助

【问题讨论】:

  • 需要更具体一些

标签: scala reactivemongo play-reactivemongo reactivemongo-play-json


【解决方案1】:

我正在使用带有 ReactiveMongo 1.0 的 Play 框架 2.8。我通常做的是,

1. 查找集合。

这将返回一些 BSONDocuments,您需要提供 BSON 读取器和写入器来将 BSONDocuments 转换为/从您的案例类中转换。您可以查看一些教程和示例here。然后,您可以使用以下代码进行一些通用查询:

    for {
        c <- database.map(_.collection(collectionName))
        r <- c.find(selector.getOrElse(BSONDocument()), projection)
            .sort(sorter.getOrElse(BSONDocument()))
            .cursor[T]().collect[List](Int.MaxValue, Cursor.FailOnError[List[T]]())
    } yield r

2.以JSON格式返回查询结果

当您检索到查询结果后,您可以使用 Json.toJson() 以 JSON 格式返回它们,这将隐式调用案例类的 JSON readers/writers

Person.find().map {
    item => {
        Ok(Json.toJson(item))
    }
}

我没有使用 bson2json,我想在后台将案例类转换为 JSON 会有所帮助。

【讨论】:

    猜你喜欢
    • 2010-12-11
    • 2022-01-10
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    相关资源
    最近更新 更多