0

私たちのプロジェクトでは、Scala と Reactivemongo を使用しています。(私は両方とも非常に新しいです)「きれいな」Bsonをコンソールに出力すると、次のようになります。

{  _id: BSONObjectID("52b006fe0100000100d47242"),
desc: BSONString({"_id:"BSONObjectID(52af03a5010000010036194d),"desc:"BSONString(www.foo.com"hits),"domains:"["0:"BSONString(www.foo.com)"],"func:"BSONString(Count),"maxr:"BSONInteger(5),"props:"["]"} hits),
domains: [
0: BSONString(jsonString)
],
func: BSONString(Count),
maxr: BSONInteger(5),
props: [
]
}

コンソールから対応するケース クラスに解析できるようにする必要があります。

何か助けてください。

4

3 に答える 3

1

typesafe の activator テンプレートから取得したもので、Json.format をケース クラスのコンパニオン オブジェクト (ReactiveMongo 0.9、scala 2.10.2) で暗黙の val として使用するだけです。例:

package models

import play.api.libs.json.Json
import reactivemongo.bson.BSONObjectID
import play.modules.reactivemongo.json.BSONFormats._

/**
 * A message class
 *
 * @param _id The BSON object id of the message
 * @param message The message
 */
case class Message(_id: BSONObjectID, message: String)

object Message {
  /**
   * Format for the message.
   *
   * Used both by JSON library and reactive mongo to serialise/deserialise a message.
   */
  implicit val messageFormat = Json.format[Message]
}

私はそれを使用しています.JSONがそれらをフォーマットする方法を知っている限り、より多くのパラメーターを使用できます.

package models

import play.api.libs.json.Json
import reactivemongo.bson.BSONObjectID
import play.modules.reactivemongo.json.BSONFormats._

/**
 * A message class
 *
 * @param _id The BSON object id of the message
 * @param message The message
 */

case class Name(fName: String, lName: String, mInitial: String)

object Name {
  implicit val nameFormat = Json.format[Name]
}

case class Message(_id: BSONObjectID, message: String, name: Name)

object Message {
  /**
   * Format for the message.
   *
   * Used both by JSON library and reactive mongo to serialise/deserialise a message.
   */
  implicit val messageFormat = Json.format[Message]
}

補助コンストラクターがある場合、またはコンパニオンに apply(...) を実装する場合、私はまだそれを行う方法を考え出していません。ただし、コンパイラはそのことを警告します。

于 2013-12-17T22:24:16.037 に答える
0

Reactivemongo ドキュメントのこのリンクで、彼らがどのようにそれを行ったかを確認できます: http://stephane.godbillon.com/2012/10/18/writing-a-simple-app-with-reactivemongo-and-play-framework-pt- 1.html

implicit object ArticleBSONReader extends BSONReader[Article] {
def fromBSON(document: BSONDocument) :Article = {
  val doc = document.toTraversable
  Article(
    doc.getAs[BSONObjectID]("_id"),
    doc.getAs[BSONString]("title").get.value,
    doc.getAs[BSONString]("content").get.value,
    doc.getAs[BSONString]("publisher").get.value,
    doc.getAs[BSONDateTime]("creationDate").map(dt => new DateTime(dt.value)),
    doc.getAs[BSONDateTime]("updateDate").map(dt => new DateTime(dt.value)))
  }
}
于 2013-12-17T14:53:34.277 に答える