使用格式优于读写

时间:2018-06-22 05:49:53

标签: playframework-2.6

Play Framework提到Format,它们使用ReadsWrites创建Json来对转换器进行建模,反之亦然。我无法理解使用Format的好处,因为无论如何我都必须写ReadsWrites(除非ReadsWrites是对称的) 。为什么我应该使用Format

来自文档

val locationReads: Reads[Location] = (
  (JsPath \ "lat").read[Double](min(-90.0) keepAnd max(90.0)) and
  (JsPath \ "long").read[Double](min(-180.0) keepAnd max(180.0))
)(Location.apply _)

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

implicit val locationFormat: Format[Location] =
  Format(locationReads, locationWrites)

如果您的读写是对称的(在实际应用中可能不是这种情况),则可以直接从组合器定义格式:

implicit val locationFormat: Format[Location] = (
  (JsPath \ "lat").format[Double](min(-90.0) keepAnd max(90.0)) and
  (JsPath \ "long").format[Double](min(-180.0) keepAnd max(180.0))
)(Location.apply, unlift(Location.unapply))

0 个答案:

没有答案