json-lenses icon indicating copy to clipboard operation
json-lenses copied to clipboard

Type conversion doesn't handle explicit nulls

Open ianp opened this issue 10 years ago • 3 comments

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)?

ianp avatar Nov 19 '14 15:11 ianp

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.

ianp avatar Nov 19 '14 17:11 ianp

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?

JD557 avatar Oct 26 '15 11:10 JD557

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.

jeroenr avatar Jun 23 '16 13:06 jeroenr