1

I understand this shouldn't happen, but a 3rd party API is returning JSON response, with the exact same field EITHER as Double/Float or as a String. After much internal debate of "why we live in a world like this", I'm struggling to find a way to parse such a response:

implicit val inconsistentReads: Reads[InconsistentItem] = (
  (JsPath \ "field").readNullable[String] ... 
)(InconsistentItem.apply _)

When this runs, I'm getting "play.api.libs.json.JsResultException: JsResultException" when the field sometimes is returned as a numeric value.

Would it be possible to read it in as String, regardless of if it was numeric or String in the Json response?

This is for Scala in Play Framework. Much thanks!

1 Answer 1

4

Try something like this. Since you don't define what InconsistentItem is, I use Either.

val inconsistentReads = Reads[Either[String, BigDecimal]] {
     case JsNumber(a) => JsSuccess(Right(a))
     case JsString(a) => JsSuccess(Left(a))
     case _ => JsError("Type not supported")
     }

Examples:

Json.parse("\"hi\"").validate[Either[String, BigDecimal]](inconsistentReads)
# JsSuccess(Left("hi"))
Json.parse("1").validate[Either[String, BigDecimal]](inconsistentReads)
# JsSuccess(Right(1))
Sign up to request clarification or add additional context in comments.

1 Comment

A more generic defintion of Reads[Either]: gist.github.com/graingert/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.