如果您有 Reads[T] 和 Writes [T],那么 Format[T] 的目的是什么?

What is the purpose of Format[T] if you have a Reads[T] and Writes [T]?

我只花了几个小时来探索 Play Framework (2.5.1),我很困惑你为什么要在已经定义了 ReadsWrites 的情况下创建 Format .通过为您的 class 定义 ReadsWrites,您是否定义了将 class 与 JsValue 相互转换所需的所有功能?

如播放框架文档中所述here

Format[T] is just a mix of the Reads and Writes traits and can be used for implicit conversion in place of its components.

格式是读取[T] 和写入[T] 的组合。因此,您可以为类型 T 定义一个隐式 Format[T] 并使用它来读取和写入 Json,而不是为类型 T 定义单独的隐式 Reads[T] 和 Writes[T]。因此,如果您已经拥有为您的类型 T 定义的 Reads[T] 和 Writes[T] 然后不需要 Format[T] ,反之亦然。

Format 的一个优点是您可以为类型 T 定义单个隐式格式 [T],而不是定义两个单独的 Reads[T] 和 Writes[T],如果它们都是对称的(即读取和写入).因此 Format 使您的 JSON 结构定义不那么重复。例如你可以这样做

implicit val formater: Format[Data] = (
    (__ \ "id").format[Int] and
    (__ \ "name").format[String] and
    (__ \ "value").format[String]
  ) (Data.apply, unlift(Data.unapply))

而不是这个。

implicit val dataWriter: Writes[Data] = (
    (__ \ "id").write[Int] and
    (__ \ "name").write[String] and
    (__ \ "file_type").write[String]
  ) (Data.apply)

implicit val dataWriter: Reads[Data] = (
    (__ \ "id").read[Int] and
    (__ \ "name").read[String] and
    (__ \ "file_type").read[String]
  ) (unlift(Data.unapply))