未找到Json格式化程序Scala,播放框架错误

未找到Json格式化程序Scala,播放框架错误,scala,playframework,Scala,Playframework,我有以下两个含义 implicit val readObjectIdFormat = new Reads[ObjectId] { def reads(jv: JsValue): JsResult[ObjectId] = { JsSuccess(new ObjectId(jv.as[String])) } } implicit val visitorFormat = ( (__ \ "_id").formatOpt[ObjectId] and (__ \ "visitorId").form

我有以下两个含义

implicit val readObjectIdFormat = new Reads[ObjectId] {
def reads(jv: JsValue): JsResult[ObjectId] = {
  JsSuccess(new ObjectId(jv.as[String]))
 }
}

implicit val visitorFormat = (
(__ \ "_id").formatOpt[ObjectId] and
(__ \ "visitorId").format[String] and
(__ \ "referralUrl").formatOpt[String] and
(__ \ "ipAddress").formatOpt[String] and
(__ \ "promotionId").format[String])(Visitor)  
虽然ReadObjectedFormat是在编译时定义的,但它在“(\uu\“\ uID”).formatOpt[ObjectId]”行上一直在抱怨

找不到类型org.bson.types.ObjectId的Json格式化程序。尝试实现隐式 此类型的格式。

版本:Play 2.1-RC2,Scala 2.10


知道它为什么不识别ReadObjectedFormat吗?

您正在实现
读取
,您需要实现
格式

implicit val readObjectIdFormat = new Format[ObjectId] {
 def reads(jv: JsValue): JsResult[ObjectId] = {
  JsSuccess(new ObjectId(jv.as[String]))
 }

 def writes(o: A): JsValue = JsString(...)
}
或者您需要使用read而不是format(注意,我假设这对read有效,但还没有测试它)

From:
Format[T]用写[T]扩展读[T]

格式
是一种读+写

然后编写一个隐式writeObjectdFormat

implicit val formatObjectIdFormat = 
   Format(readObjectIdFormat, writeObjectIdFormat)

其他人给出了很好的答案,用格式代替。 顺便说一下,您可以处理解析错误

此实现对我来说运行良好:

  implicit val objectIdFormat: Format[ObjectId] = new Format[ObjectId] {

    def reads(json: JsValue) = {
      json match {
        case jsString: JsString => {
          if ( ObjectId.isValid(jsString.value) ) JsSuccess(new ObjectId(jsString.value))
          else JsError("Invalid ObjectId")
        }
        case other => JsError("Can't parse json path as an ObjectId. Json content = " + other.toString())
      }
    }

    def writes(oId: ObjectId): JsValue = {
      JsString(oId.toString)
    }

  }

谢谢就这样。在使用隐式val visitorReadFormat=Json.reads[Visitor]等简洁易读的版本深入研究文档和宏之后
  implicit val objectIdFormat: Format[ObjectId] = new Format[ObjectId] {

    def reads(json: JsValue) = {
      json match {
        case jsString: JsString => {
          if ( ObjectId.isValid(jsString.value) ) JsSuccess(new ObjectId(jsString.value))
          else JsError("Invalid ObjectId")
        }
        case other => JsError("Can't parse json path as an ObjectId. Json content = " + other.toString())
      }
    }

    def writes(oId: ObjectId): JsValue = {
      JsString(oId.toString)
    }

  }