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