简体   繁体   中英

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

I have two controllers who writes and reads the same AccountModel case class. 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)] ).

I would like to reuse this AccountModel and his implicits Writes and Reads but don't know how the achieve that 'the scala way'.

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.


What are you used to do, where do you put your reusable Json classes, do you have some advices ?

Thanks a lot

There are two main approaches.

Approach 1: Put them on a companion object of your serializable object:

// 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.

Approach 2: Prepare a trait with JSON formatters:

// 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. 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. Thanks for pointing it out in the comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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