【问题标题】:Play ScalaJSON Reads[T] parsing ValidationError(error.path.missing,WrappedArray())播放 ScalaJSON Reads[T] 解析 ValidationError(error.path.missing,WrappedArray())
【发布时间】:2014-02-12 19:37:30
【问题描述】:

我有一个有趣的 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"
} ]

我编写了案例类和自定义读取:

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

当我验证提供的数据时:

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 来访问它

val switches: Seq[String] = (json \\ "switch_id").map(_.as[String])

但我真的对我在自定义读取方面做错了什么感到束手无策。 我试过放另一个顶级键和其他组合,但似乎我错过了一些重要的东西,因为我今天才开始这样做。

非常感谢。

【问题讨论】:

    标签: json scala playframework


    【解决方案1】:

    错误告诉您,它不是/switch_id,而是一个数组。因此,您似乎应该将 JSON 读取为 List[Switch] 而不仅仅是 Switch

    假设您的 Reads(没有测试它们)是正确的,这应该可以:

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

    【讨论】:

    • 谢谢。确实至关重要。我错过了它的语义。并尝试添加开关来处理根级别。哈哈哈,这样不行。祝福你。
    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    相关资源
    最近更新 更多