Skip to content

Instantly share code, notes, and snippets.

@imanabu
Last active May 14, 2020 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imanabu/5815e2b6231e122da2b876c6fbe4d2f8 to your computer and use it in GitHub Desktop.
Save imanabu/5815e2b6231e122da2b876c6fbe4d2f8 to your computer and use it in GitHub Desktop.
implicit converter lets you read Json into Option[Double] Scala Data Type
object DoubleReads {
def reads(json: JsValue): JsResult[Option[Double]] = json match {
case JsNumber(n) => JsSuccess(Some(n.toDouble))
case JsString(s) => JsSuccess(Some(s.toDouble))
case _ => JsSuccess(None)
}
}
// Later in your code where you need
implicit val odr: json.Reads[Option[Double]] = DoubleReads.reads
// then you can
val data = Json.fromJson[ObjContainingOptionDouble](json)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment