如何取消限制Spray jsonFormat

编程入门 行业动态 更新时间:2024-10-26 15:28:19
本文介绍了如何取消限制Spray jsonFormat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在实现一些使用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

本文发布于:2023-11-25 04:17:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628290.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Spray   jsonFormat

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!