2

I am building REST API using spray. All is working well except this case class:

case class User(name: String, places: List[String], data: List[JsObject])

The key issue here is the data parameter. It contains a json object with arbitrary number of members, types, and levels - but still valid json.

Using spray, I am able to serialize/deserialize a request/response properly using:

object UserProtocol extends DefaultJsonProtocol {
  implicit val userResonseFormat = jsonFormat3(User)
}

// ...

import demo.UserProtocol._

post {
  path("users") {
    entity(as[User]) { user: User =>
      complete(user)
    }
  }
}

The problem is reading and writing BSON for reactivemongo. I cannot seem to figure out how to complete these:

implicit object UserWriter extends BSONDocumentWriter[User] {
  def write(user: User): BSONDocument = BSONDocument(
    "name" -> user.name,
    "places" -> user.places,
    "data" -> ???
}

implicit object UserReader extends BSONDocumentReader[User] {
  def read(doc: BSONDocument): User = {
    User(
      doc.getAs[String]("name").get,
      doc.getAs[List[String]]("places").get,
      ???
  }
}

In the places of ???, How can I get this arbitrary JSON branch to serialize/deserialize BSON properly for reactivemongo?

IUnknown
  • 2,596
  • 4
  • 35
  • 52

1 Answers1

0

This is a simple example that illustrate how to define readers and writers for a model. Hope it helps.

https://github.com/luongbalinh/play-mongo/blob/master/app/models/User.scala

Luong Ba Linh
  • 802
  • 5
  • 20