取自 typesafe 的激活器模板,您可以简单地将 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(...),我仍然没有想出办法。但是,编译器会提醒您注意这一点。