json - 玩2 Json格式,捕获Int或String

标签 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))

如果 c 为空或不存在或者是一个字符串,效果很好,但如果 c 是一个整数,则会出现此错误: ValidationError(List(error.expected.jsstring),WrappedArray()))

如果 c 是一个整数,我会得到,或者将其转换为字符串或放入 c=None

最佳答案

你可以这样做。

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

关于json - 玩2 Json格式,捕获Int或String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32209959/

相关文章:

json - 使用lift-json将Json值提取为Map

php - Android:如何从远程服务器获取图像

php - (array) type cast strange behavior object to array 转换

java - Play 框架 - 如何模拟 render() 方法?

scala - 如何确保 Play! 中文件上传的安全框架(斯卡拉)

javascript - 如何将图像填充为链接,并将其作为 JSON 对象存储在数组中?

string - 将字符串表达式转换为实际工作实例表达式

java - Heroku JVM 调优

scala - SBT 中作用域库依赖项的特定语法?

playframework - 如何访问 Play Guice 模块中的请求?