scalajson4s

Deserializing Option returns None instead of an exception in json4s


When running the following code I would expect an exception, but I get None instead. Is that expected?

import org.json4s.jackson.JsonMethods
import org.json4s.{DefaultFormats, Formats}
implicit val f: Formats = DefaultFormats
val json ="{ \"a\" : { \"c\": 1 }}"

case class Foo(a: Option[String])
val foo = JsonMethods.parse(json).extract[Foo]

println(foo)

>  Foo(None)

also that code:

import org.json4s.jackson.JsonMethods
import org.json4s.{DefaultFormats, Formats}
implicit val f: Formats = DefaultFormats
val json ="{ \"a\" : { \"c\": 1 }}"

case class Foo(a: String = "")
val foo = JsonMethods.parse(json).extract[Foo]

println(foo)

>  Foo()

Solution

  • You can enforce strict option parsing by changing the default format as such:

    implicit val f: Formats = DefaultFormats.withStrictOptionParsing
    

    The underlying exception:

    [error] (run-main-2) org.json4s.package$MappingException: No usable value for a
    [error] Do not know how to convert JObject(List((c,JInt(1)))) into class java.lang.String