播放2个Json格式,捕获Int或String

fas*_*r2b 2 json scala playframework

我有一个问题,我使用休息网络服务而不是返回格式不正确的 json,有时返回一个字符串,有时返回同一字段中的整数。这是格式的代码:

implicit val ItemFormat: Format[Item] = (
  (JsPath \ "a").format[String] and
    (JsPath \ "b").format[String] and
    (JsPath \ "c").formatNullable[String]
  )(Item.apply , unlift(Item.unapply))
Run Code Online (Sandbox Code Playgroud)

如果 c 为空或不存在或者是一个字符串,但如果 c 是一个整数我有这个错误: ValidationError(List(error.expected.jsstring),WrappedArray()))

我会得到,如果 c 是一个整数,或者把它转换成一个字符串或者把 c=None

Tyt*_*yth 5

你可以这样做。

case class Item(a: String, b: String, c: Option[String])

implicit val reads: Reads[A] = new Reads[A] { 
  override def reads(json: JsValue): JsResult[A] = { 
    for {
      a <- (json \ "a").validate[String]
      b <- (json \ "b").validate[String]
    } yield {
      val cValue = (json \ "c")
      val cOptString = cValue.asOpt[String].orElse(cValue.asOpt[Int].map(_.toString))
      Item(a, b, cOptString)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)