Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

json - Play ScalaJSON Reads[T] parsing ValidationError(error.path.missing,WrappedArray())

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])

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Assuming your Reads (didn't test them) are correct this should work:

val json: JsValue = Json.parse(jsonChunk)
println(json.validate[List[TheSwitch]])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...