4

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()
Szymon Jednac
  • 2,969
  • 1
  • 29
  • 43
igreenfield
  • 1,618
  • 19
  • 36

1 Answers1

4

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
Szymon Jednac
  • 2,969
  • 1
  • 29
  • 43