简体   繁体   English

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

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

I have two controllers who writes and reads the same AccountModel case class. 我有两个编写和读取相同AccountModel案例类的控制器。 This class is an adapter for my "domain" object Account who flatten some collections and transform objects references ( Map[Role, Auth] ) to a explicit key reference ( Set[AuthModel(rolekey:String, level:Int)] ). 此类是我的“域”对象Account的适配器,该对象将一些集合展平并将对象引用( Map[Role, Auth] )转换为显式键引用( Set[AuthModel(rolekey:String, level:Int)] )。

I would like to reuse this AccountModel and his implicits Writes and Reads but don't know how the achieve that 'the scala way'. 我想重用此AccountModel及其隐式的WritesReads但不知道如何实现“ scala方式”。

I would say in an object Models with my case classes as inner classes and all the related implicits but I think that this would become unreadable soon. 我想在一个object Models中将我的案例类作为内部类以及所有相关的隐式对象,但是我认为这很快将变得难以理解。


What are you used to do, where do you put your reusable Json classes, do you have some advices ? 您过去经常做什么,将可重用的Json类放在哪里,有什么建议吗?

Thanks a lot 非常感谢

There are two main approaches. 主要有两种方法。

Approach 1: Put them on a companion object of your serializable object: 方法1:将它们放在可序列化对象的伴随对象上:

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

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

This way everywhere you import AccountModel , the formatters will be also available, so everything will work seamlessly. 这样,无论您在AccountModel导入AccountModel ,格式化程序都将可用,因此所有内容都将无缝运行。

Approach 2: Prepare a trait with JSON formatters: 方法2:使用JSON格式化程序准备特征:

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

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

With this approach whenever you need serialization, you have to mix the trait in, like this: 使用这种方法,每当需要序列化时,都必须将特征混合在一起,如下所示:

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

EDIT: I forgot to add a comparison of the two approaches. 编辑:我忘了添加两种方法的比较。 I usually stick to approach 1, as it is more straightforward. 我通常会坚持方法1,因为它更直接。 The JSONSupport mixin strategy is however required when you need two different formatters for the same class or when the model class is not your own and you can't modify it. 但是,当同一类需要两个不同的格式化程序,或者模型类不是您自己的并且不能修改时,则需要JSONSupport mixin策略。 Thanks for pointing it out in the comments. 感谢您在评论中指出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM