No Json Scala formatting found

I have two tracks.

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) 

Although readObjectIdFormat is determined at compile time, it continues to complain about "(__ \" _id "). FormatOpt [ObjectId]" line

There is no Json formatting for type org.bson.types.ObjectId. Try to implement an implicit format for this type.

: playback 2.1-RC2, Scala 2.10

Any idea why it doesn't recognize readObjectIdFormat?

+6
source share
3 answers

From documentation : Format[T] extends Reads[T] with Writes[T]
Format is read + write .

Write an implicit writeObjectIdFormat, then

 implicit val formatObjectIdFormat = Format(readObjectIdFormat, writeObjectIdFormat) 
0
source

Others gave a good answer, use the format instead. By the way, you can handle parsing errors.

This implementation works fine for me:

  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) } } 
+3
source

You implement Reads , and you need to implement Format .

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

Or you need to use reading instead of format (note, I assume this works for reading, did not check it).

 implicit val visitorRead = ( (__ \ "_id").readOpt[ObjectId] and (__ \ "visitorId").read[String] and (__ \ "referralUrl").readOpt[String] and (__ \ "ipAddress").readOpt[String] and (__ \ "promotionId").read[String])(Visitor) 
+2
source

All Articles