【发布时间】:2019-12-06 21:30:10
【问题描述】:
我正在尝试将使用播放框架的 json 解析为案例类。我的目的是检查 json 中是否存在特定路径。如果存在,则仅读取该路径处的元素。
这是我的代码
package com.learning.avinash.query
import play.api.libs.json.{JsDefined, JsPath, Json, Reads, Writes, __}
import play.api.libs.functional.syntax._
object ParseJson extends App {
case class Msisdn(primaryId: Option[String], relatedAccountId: Option[String])
object Msisdn {
implicit val readData: Reads[Msisdn] = (
(JsPath \ "primary-id").readNullable[String] ~
(JsPath \ "meta" \ "related-account-id").readNullable[String]
) (Msisdn.apply _)
}
val testJson = """{
"resources": [
{
"valid-for-start-datetime": "2019-08-23T10:47:17.485Z",
"primary-id": "393823468684",
"meta": {
"related-account-id": "10001771",
"roles": [
"customer"
]
}
},
{
"valid-for-start-datetime": "2019-08-23T10:47:17.485Z",
"primary-id": "393823467689"
}
]
}"""
println((Json.parse(testJson) \ "resources").as[List[Msisdn]])
}
在第二个对象的资源数组中,你可以观察到这段代码完全丢失了
"meta": {
"related-account-id": "10001771",
"roles": [
"customer"
]
}
现在当我尝试解析 json 时,它失败了,我得到了以下异常
Exception in thread "main" play.api.libs.json.JsResultException: JsResultException(errors:List(((1)/meta/related-accoount-id,List(JsonValidationError(List(error.path.missing),WrappedArray())))))
是否有一个预定义的函数/方法在起作用,以便我可以检查是否这个
(JsPath \ "meta")
存在特定路径,然后仅读取该路径中的元素。 或者我应该编写一个自定义函数来检查路径是否存在。
我可以看到一个需要 Jsvalue 的 JsDefined()。
https://www.playframework.com/documentation/2.7.x/api/scala/play/api/libs/json/index.html
final case classJsDefined(value: JsValue)
Wrapper for JsValue to represent an existing Json value.
请有任何想法、想法、帮助或建议。
【问题讨论】:
-
accoount(related-accoount-id) 中存在语法错误。当然,这不是例外的原因
标签: json scala playframework