Playframework,将 Json Writes 和 Reads 放在哪里以供重用?

Playframework, where to put Json Writes and Reads for reuse?

我有两个控制器写入和读取相同的 AccountModel 案例 class。这个 class 是我的 "domain" 对象 Account 的适配器,它展平了一些集合并将对象引用 (Map[Role, Auth]) 转换为显式键引用 (Set[AuthModel(rolekey:String, level:Int)])。

我想重用这个 AccountModel 和他的隐式 WritesReads 但不知道如何实现 'the scala way'.

我会在 object Models 中说我的案例 classes 作为内部 classes 和所有相关的隐式,但我认为这很快就会变得不可读。


你以前是做什么的,你把可重复使用的 Json class 放在哪里,你有什么建议吗?

非常感谢

主要有两种方法。

方法 1:将它们放在可序列化对象的伴随对象上:

// in file AccountModel.scala
class AccountModel(...) {
  ...
}

object AccountModel {
  implicit val format: Format[AccountModel] = {...}
}

通过这种方式,无论您在哪里导入 AccountModel,格式化程序也将可用,因此一切都将无缝运行。

方法 2:使用 JSON 格式化程序准备特征:

// in a separate file AccountModelJSONSupport.scala
import my.cool.package.AccountModel

trait AccountModelJsonSupport {
  implicit val format: Format[AccountModel] = {...}
}

使用这种方法,只要你需要序列化,你就必须混合特征,就像这样:

object FirstController extends Controller with AccountModelJsonSupport {
  // Format[AccountModel] is available now:
  def create = Action(parse.json[AccountModel]) { ... }
}

编辑:我忘了添加两种方法的比较。我通常坚持方法 1,因为它更直接。然而,当您需要两个不同的格式化程序用于相同的 class 或者当模型 class 不是您自己的并且您无法修改它时,需要使用 JSONSupport mixin 策略。感谢您在评论中指出。