Is it possible to make json4s not to throw exception when required field is missing ?
When I "extract" object from raw json string it throws exception like this one
org.json4s.package$MappingException: No usable value for pager
No usable value for rpp
Did not find value which can be converted into byte
at org.json4s.reflect.package$.fail(package.scala:98)
at org.json4s.Extraction$ClassInstanceBuilder.org$json4s$Extraction$ClassInstanceBuilder$$buildCtorArg(Extraction.scala:388)
at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$11.apply(Extraction.scala:396)
Is it possible just to let it be null ?
It's quite simple, you have to use
Option
and its potentials,Some
andNone
.Beware though, in the above case a
match
will be performed for yourOption
. If it'sNone
, it will be completely removed from the string, so it won't feed back null.In the same pattern, to parse incomplete JSON, you use a
case class
withOption
.There is a method which won't throw any exception, and that is
extractOpt
A way to replicate that with the scala API would be to use
scala.util.Try
:I've dealt with this problem when dealing with data migrations, and I wanted default values to fill undefined fields.
My solution was to merge the defaults into the JValue before extracting the result.
JsonUtil.scala