播放JSON写入如何将字段值转换为正确的字段

时间:2014-09-13 11:53:38

标签: json scala playframework playframework-2.3

我试图在更深层次上理解Writes [T],而不仅仅是接受我知道它的作品。我感到困惑的是在取消申请和解除之后T我的理解是你结束了一个价值元组。如果它们都是相同的类型,例如双打如下,它如何将这些值与正确的位置匹配?我想知道它是否与组合器的顺序有关,但是当地的实验似乎表明我的顺序并不重要。 Play Docs的ScalaJsonCombinators页面示例:

case class Location(lat: Double, long: Double)

import play.api.libs.json._
import play.api.libs.functional.syntax._

implicit val locationWrites: Writes[Location] = (
 (JsPath \ "lat").write[Double] and
 (JsPath \ "long").write[Double]
)(unlift(Location.unapply))

1 个答案:

答案 0 :(得分:2)

它绝对与组合符的顺序与Location.unapply中的字段顺序有关,否则将无法确定性地编写ReadsWrites

implicit val locationWrites: Writes[Location] = (
  (JsPath \ "lat").write[Double] and
  (JsPath \ "long").write[Double]
)(unlift(Location.unapply))

scala> Json.stringify(Json.toJson(Location(2.11, 42.12)))
res2: String = {"lat":2.11,"long":42.12}

Writes中的路径名与Location的字段名称无关,只是按顺序应用它们:

// Reversed
implicit val locationWrites: Writes[Location] = (
  (JsPath \ "long").write[Double] and
  (JsPath \ "lat").write[Double]
)(unlift(Location.unapply))

scala> Json.stringify(Json.toJson(Location(2.11, 42.12)))
res3: String = {"long":2.11,"lat":42.12}