当前位置: 动力学知识库 > 问答 > 编程问答 >

scala - How to avoid coupling to a representation in Play 2.3?

问题描述:

The RESTful example Action in the Play 2.3 docs reads:

def listPlaces = Action {

val json = Json.toJson(Place.list)

Ok(json)

}

What makes the method tightly coupled to this specific JSON format.

Is it possible to have the service logic separated from content representation, for example as JAX-RS does with MessageBody Writers and Readers?

网友答案:

Ok(json) is actually calling Status.apply. It requires a play.api.http.Writeable[A], which is something that can transform A to a byte array and return the content type for A. In your case A stands for JsValue.

What you can do is to go a step further and supply a Writeable[Place], so you can write something like this:

def listPlaces(implicit writeable: Writeable[Place]) = Action {
  Ok(Place.list)
}

I assume you already have a Writes[Place]. All that's left is to implement a generic function that converts json Writes to http Writeable:

implicit def jsonWritesToHttpWriteable[A](jsWrites: Writes[A])
                                         (implicit writeable: Writeable[JsValue]): Writeable[A] =
  writeable.map(jsWrites.writes)

Now, having defined this conversion function as implicit, you can just supply the Writes[Place] when you call listPlaces:

val listPlacesJson = listPlaces(placeJsonWrites)

Of course, your route must point to listPlacesJson now.

分享给朋友:
您可能感兴趣的文章:
随机阅读: