我正在实现一些使用spray和akka的rest API.该API应该公开某种用户CRUD.在这个问题中,我将仅使用创建用户...
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] } } }现在让我们假设User类有30个字段 但是没有jsonFormat30(...) 我该如何对任何case类对象使用此类隐式?
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?
推荐答案如果要引用ProductFormatsInstances特征中的方法,则存在jsonFormat版本,最多22个参数.如果您的案例类具有22个以上的参数,则可以看到两个立即选择.假设你有
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, ...)
-
选项1:通过将Client类分解为带有较少参数的更细粒度的类来减少参数的数量.例如,您可以重构为以下内容.
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, ...)-
选项2:通过实现RootJsonFormat编写自定义序列化程序.有关示例,请参见此处.
Options 2: write a custom serialiser by implementing RootJsonFormat. See here for an example.
更多推荐
如何取消限制Spray jsonFormat
发布评论