Reputation: 672
I have a problem, I use an rest webservice than return an json not well formatted, sometimes return a string sometimes an integer in the same field. This is the code of the format:
implicit val ItemFormat: Format[Item] = (
(JsPath \ "a").format[String] and
(JsPath \ "b").format[String] and
(JsPath \ "c").formatNullable[String]
)(Item.apply , unlift(Item.unapply))
If c is empty or not exist or is a string works well, but if the c is an integer I have this error: ValidationError(List(error.expected.jsstring),WrappedArray()))
I would obtain, if c is an integer, or convert it in a string or put c=None
Upvotes: 2
Views: 740
Reputation: 1824
You can do it this way.
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)
}
}
}
Upvotes: 5