How to unlimit spray jsonFormat

元气小坏坏 提交于 2019-12-01 05:40:17

问题


I'm implementing some rest API that use spray and akka The API should expose some kind of user CRUD. I'll use only create user in this question...

case class User(id:String, name:String)  
case class Register(user:User, registrationId:String) 

trait DefaultJsonFormats extends DefaultJsonProtocol with SprayJsonSupport with MetaMarshallers {}

class RegistrationService(registration: ActorRef)
   (implicit executionContext: ExecutionContext) 
                   extends Directives with DefaultJsonFormats {
  implicit val timeout = Timeout(2.seconds)
  implicit val userFormat = jsonFormat3(User)
  implicit val registerFormat = jsonFormat1(Register)
  implicit val registeredFormat = jsonFormat1(Registered)

  val route =
      path("register") {
          post {  handleWith { ru: Register => (registration ?   ru).mapTo[Registered] } }
}

Now Lets suppose that User class has 30 fields but there is no jsonFormat30(...) How can I use such implicits for any case class object?


回答1:


If you are referring to the methods in the ProductFormatsInstances trait, there are versions of jsonFormat up to 22 parameters. If you have a case class with more than 22 parameters, I see two immediate options. Suppose you have

case class Client(..., address: Address, telephone: Telephone, email: Email, ...)
  • Options 1: reduce the number of parameters by breaking down the Client class into finer-grained classes taking fewer parameters.. For example, you can refactor to the following.

    case class ClientContact(address: Address, telephone: Telephone, email: Email)
    case class Client(..., contact: ClientContact, ...)
    
  • Options 2: write a custom serialiser by implementing RootJsonFormat. See here for an example.



来源:https://stackoverflow.com/questions/33494526/how-to-unlimit-spray-jsonformat

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!