scala 播放 ScalaJSON Reads[T] 解析 ValidationError(error.path.missing,WrappedArray())
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21737897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Play ScalaJSON Reads[T] parsing ValidationError(error.path.missing,WrappedArray())
提问by FoggyDew
i have a funny json data looking as:
我有一个有趣的 json 数据,如下所示:
[ {
"internal_network" : [ {
"address" : [ {
"address_id" : 2,
"address" : "172.16.20.1/24"
}, {
"address_id" : 1,
"address" : "172.16.30.30/24"
} ]
} ],
"switch_id" : "0000000000000001"
}, {
"internal_network" : [ {
"address" : [ {
"address_id" : 2,
"address" : "172.16.30.1/24"
}, {
"address_id" : 1,
"address" : "192.168.10.1/24"
}, {
"address_id" : 3,
"address" : "172.16.10.1/24"
} ]
} ],
"switch_id" : "0000000000000002"
} ]
i wrote case classes and custom reads:
我写了案例类和自定义读取:
case class TheAddress(addr: (Int, String))
implicit val theAddressReads: Reads[TheAddress] = (
(__ \ "address_id").read[Int] and
(__ \ "address").read[String] tupled) map (TheAddress.apply _)
case class Addresses(addr: List[TheAddress])
implicit val addressesReads: Reads[Addresses] =
(__ \ "address").read(list[TheAddress](theAddressReads)) map (Addresses.apply _)
case class TheSwitch(
switch_id: String,
address: List[Addresses] = Nil)
implicit val theSwitchReads: Reads[TheSwitch] = (
(__ \ "switch_id").read[String] and
(__ \ "internal_network").read(list[Addresses](addressesReads)))(TheSwitch)
case class Switches(col: List[TheSwitch])
implicit val switchesReads: Reads[Switches] =
(__ \ "").read(list[TheSwitch](theSwitchReads)) map (Switches.apply _)
when i validate the provided data with:
当我验证提供的数据时:
val json: JsValue = Json.parse(jsonChunk)
println(json.validate[TheSwitch])
i get:
我得到:
JsError(List((/switch_id,List(ValidationError(error.path.missing,WrappedArray()))), (/internal_network,List(ValidationError(error.path.missing,WrappedArray())))))
i can access it with JsPath like
我可以像 JsPath 一样访问它
val switches: Seq[String] = (json \ "switch_id").map(_.as[String])
but i'm really at my wits end with what am i doing wrong with custom reads. i've tried with putting another top level key, and other combinations, but seems i'm missing something crucial, since i've started with this just today.
但我真的不知所措,因为我在自定义读取上做错了什么。我试过放置另一个顶级键和其他组合,但似乎我错过了一些重要的东西,因为我今天才开始使用它。
thanks a lot.
多谢。
采纳答案by serejja
The error is telling you that instead of /switch_idit got an array. So it seems like you should read the JSON as a List[Switch]instead of just Switch
错误告诉你它不是/switch_id得到一个数组。因此,您似乎应该将 JSON 读作 aList[Switch]而不仅仅是Switch
Assuming your Reads(didn't test them) are correct this should work:
假设你的Reads(没有测试它们)是正确的,这应该有效:
val json: JsValue = Json.parse(jsonChunk)
println(json.validate[List[TheSwitch]])

