【问题标题】:Play JSON Writes how it gets field values into correct field播放 JSON 写入如何将字段值放入正确的字段
【发布时间】:2014-09-13 11:53:38
【问题描述】:

我试图在更深层次上理解 Writes[T],而不是仅仅接受它的工作原理,我知道它确实有效。我感到困惑的是,在取消应用和提升 T 之后,我的理解是你以一组值结束。如果它们都是相同的类型,例如下面的 Doubles,它如何将这些值匹配到正确的位置?我想知道它是否与组合器的顺序有关,但本地实验似乎告诉我顺序并不重要。 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))

【问题讨论】:

    标签: json scala playframework playframework-2.3


    【解决方案1】:

    这绝对与组合符的顺序与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}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-14
      • 2021-07-21
      • 2017-04-13
      • 1970-01-01
      • 2016-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多