0

I want to avoid Runtime undefined behaivors as follows:

val jsonExample = Json.toJson(0)
jsonExample.asOpt[Instant]

yield Some(1970-01-01T00:00:00Z)

How can I verify this using partial function with a lift or some other way, to check thatits indeed Instant, or how you recommend to validate?

ex1:
val jsonExample = Json.toJson(Instant.now())
jsonExample match { ... }

ex2:
val jsonExample = Json.toJson(0)
jsonExample match { ... }

Examples for desired output:

validateInstant(Json.toJson(Instant.now())) -> return Some(...)
validateInstant(Json.toJson(0)) -> return None

I can do somthing as follows, maybe some other ideas?

Just wanted to add a note regarding parsing json, there some runtime undefined problems when we are trying to parse .asOpt[T] for example:

Json.toJson("0").asOpt[BigDecimal] // yields Some(0)
Json.toJson(0).asOpt[Instant] // yields Some(1970-01-01T00:00:00Z)
We can validate it as follows or some other way:
Json.toJson("0") match {
  case JsString(value) => Some(value)
  case _ => None
}

Json.toJson(0) match {
  case JsNumber(value) => Some(value)
  case _ => None
}

Json.toJson(Instant.now()) match {
  case o @ JsString(_) => o.asOpt[Instant]
  case _ => None
}

1 Answer 1

1

You can use Option:

def filterNumbers[T](value: T)(implicit tjs: Writes[T]): Option[Instant] = {
  Option(Json.toJson(value)).filter(_.asOpt[JsNumber].isEmpty).flatMap(_.asOpt[Instant])
}

Then the following:

println(filterNumbers(Instant.now()))
println(filterNumbers(0))

will output:

Some(2021-02-22T10:35:13.777Z)
None
2
  • Thanks Tomer Shetah, is there a way like i suggested but with lift as a partial function, without the case _ => None?
    – Zvi Mints
    Commented Feb 22, 2021 at 11:04
  • 1
    Please note that json.parse returnsJsValue. If you do pattern matching on it which is not exhaustive, you'll get an exception that is saying that. It is not a good practice. Therefore I think that using Option is better. Commented Feb 22, 2021 at 16:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.