我正在实现一些使用 Spray 和 akka 的 REST API,该 API 应该公开某种用户 CRUD。我将在这个问题中仅使用创建用户......
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(...)
如何对任何案例类对象使用此类隐式?
如果您参考的是ProductFormatsInstances
特征,有多个版本jsonFormat
最多 22 个参数。如果您的案例类包含超过 22 个参数,我会看到两个直接选项。假设你有
case class Client(..., address: Address, telephone: Telephone, email: Email, ...)
-
选项 1:通过分解来减少参数数量Client
将类划分为采用更少参数的更细粒度的类。例如,您可以重构为以下内容。
case class ClientContact(address: Address, telephone: Telephone, email: Email)
case class Client(..., contact: ClientContact, ...)
选项 2:通过实现来编写自定义序列化程序RootJsonFormat
. See here举个例子。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)