问题描述
我有一个有趣的json数据,看起来是:
i have a funny json data looking as:
[ {
"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])
我得到:
JsError(List((/switch_id,List(ValidationError(error.path.missing,WrappedArray()))), (/internal_network,List(ValidationError(error.path.missing,WrappedArray())))))
我可以像使用JsPath一样访问它
i can access it with JsPath like
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.
非常感谢.
推荐答案
错误告诉您,它不是数组,而是/switch_id
.因此,似乎您应该将JSON读为List[Switch]
而不是Switch
The error is telling you that instead of /switch_id
it got an array. So it seems like you should read the JSON as a List[Switch]
instead of just Switch
假设您的Reads
(未测试它们)是正确的,这应该可以工作:
Assuming your Reads
(didn't test them) are correct this should work:
val json: JsValue = Json.parse(jsonChunk)
println(json.validate[List[TheSwitch]])
这篇关于播放ScalaJSON Reads [T]解析ValidationError(error.path.missing,WrappedArray())的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!