【问题标题】:What is the purpose of Format[T] if you have a Reads[T] and Writes [T]?如果您有 Reads[T] 和 Writes [T],Format[T] 的目的是什么?
【发布时间】:2017-11-08 05:11:12
【问题描述】:

我只需要几个小时来探索Play Framework (2.5.1),我很困惑为什么在你已经定义了ReadsWrites 之后还要创建Format。通过为您的类定义ReadsWrites,您是否定义了将类转换为JsValue 和从JsValue 转换所需的所有功能?

【问题讨论】:

  • 如果你回答了你的问题可以接受吗?

标签: json scala playframework-2.0


【解决方案1】:

正如 play-framework 文档中提到的 here

Format[T] 只是 Reads 和 Writes 特征的混合,可以使用 用于代替其组件的隐式转换。

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

Format 的一个优点是您可以为您的类型 T 定义一个 Implicit Format[T],而不是定义两个单独的 Reads[T] 和 Writes[T],如果它们都是对称的(即 Reads 和 Writes)。因此 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))

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 2012-03-10
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多