播放2 Json格式,捕获整型或字符串
我有一个问题,我使用rest Web服务,而不是返回格式不好的json,有时返回字符串,有时返回同一字段中的整数。这是格式的代码:播放2 Json格式,捕获整型或字符串,json,scala,playframework,Json,Scala,Playframework,我有一个问题,我使用rest Web服务,而不是返回格式不好的json,有时返回字符串,有时返回同一字段中的整数。这是格式的代码: implicit val ItemFormat: Format[Item] = ( (JsPath \ "a").format[String] and (JsPath \ "b").format[String] and (JsPath \ "c").formatNullable[String] )(Item.apply , unlift(It
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(列表(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)
}
}
}
case类项(a:String,b:String,c:Option[String])
隐式val读取:读取[A]=新读取[A]{
重写def读取(json:JsValue):JsResult[A]={
为了{
A.