json-lenses
json-lenses copied to clipboard
Type conversion doesn't handle explicit nulls
If I have a field which may be null then it blows up on extraction:
val json = """{ "url": null }""".parseJson
json.extract[String]("url".?)
This causes a runtime exception with root cause:
spray.json.DeserializationException: Expected String as JsString, but got null
Is this an issue with son-lenses, or am I doing something wrong (a strong possibility)?
On further investigation it may be beyond the scope of lenses, it seems to be related/identical to https://github.com/spray/spray-json/issues/60.
Any updates on this?
Wrapping the optional extract in a Try should fix this:
def extract[T: Reader](p: Lens[Option]): Option[T] =
Try { p.get[T](value) }.getOrElse(None)
although it's a bit of an hack.
@jrudolph, what's you opinion on this?
If you parse it as an Option[String]
instead it will work. As a general rule of thumb: If the value is nullable, use an Option type.