gpt4 book ai didi

json - 使用 Json.format 函数后,如何从客户端发送 Json,其对应的案例类缺少字段

转载 作者:行者123 更新时间:2023-12-01 05:12:17 24 4
gpt4 key购买 nike

我有一个案例类及其伴随对象,如下所示。现在,当我发送不带 id、createdAt 和 deletedAt 字段的 JSON 时,因为我在别处设置了它们,所以我得到了 [NoSuchElementException: JsError.get] 错误。这是因为我没有设置上面的属性。

我怎样才能做到这一点并避免出现错误?

case class Plan(id: String,
companyId: String,
name: String,
status: Boolean = true,
@EnumAs planType: PlanType.Value,
brochureId: Option[UUID],
lifePolicy: Seq[LifePolicy] = Nil,
createdAt: DateTime,
updatedAt: DateTime,
deletedAt: Option[DateTime]
)

object Plan {
implicit val planFormat = Json.format[Plan]
def fromJson(str: JsValue): Plan = Json.fromJson[Plan](str).get
def toJson(plan: Plan): JsValue = Json.toJson(plan)
def toJsonSeq(plan: Seq[Plan]): JsValue = Json.toJson(plan)
}

我从客户端发送的 JSON

{
"companyId": "e8c67345-7f59-466d-a958-7c722ad0dcb7",
"name": "Creating First Plan with enum Content",
"status": true,
"planType": "Health",
"lifePolicy": []
}

最佳答案

您可以引入另一个案例类来处理来自请求的序列化:像这样

  case class NewPlan(name: String,
status: Boolean = true,
@EnumAs planType: PlanType.Value,
brochureId: Option[UUID],
lifePolicy: Seq[LifePolicy] = Nil
)

然后使用此类来填充您的 Plan 类。

关于json - 使用 Json.format 函数后,如何从客户端发送 Json,其对应的案例类缺少字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25180849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com