Skip to content

Commit

Permalink
Closes: json4s#641.
Browse files Browse the repository at this point in the history
* Fix MappingException message when parsing missing Option
  field with strict option parsing enabled
  • Loading branch information
cstroe committed Dec 20, 2019
1 parent c00e137 commit 9d609bb
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
5 changes: 2 additions & 3 deletions core/src/main/scala/org/json4s/Extraction.scala
Original file line number Diff line number Diff line change
Expand Up @@ -587,10 +587,9 @@ object Extraction {
else x
} catch {
case e @ MappingException(msg, _) =>
if (descr.isOptional &&
(!formats.strictOptionParsing || extract(json, ScalaType[Null](implicitly)) == null))
if (descr.isOptional && !formats.strictOptionParsing) {
defv(None)
else fail("No usable value for " + descr.name + "\n" + msg, e)
} else fail("No usable value for " + descr.name + "\n" + msg, e)
}
}
}
Expand Down
25 changes: 25 additions & 0 deletions tests/src/test/scala/org/json4s/ExtractionBugs.scala
Original file line number Diff line number Diff line change
Expand Up @@ -327,5 +327,30 @@ abstract class ExtractionBugs[T](mod: String) extends Specification with JsonMet
val json = Extraction.decompose(obj)
json mustEqual JObject("s" -> JString("hello"), "i" -> JInt(3))
}

"Extract error should preserve error message when strict option parsing is enabled" in {
implicit val formats = new DefaultFormats {
override val strictOptionParsing: Boolean = true
}

val obj = parse("""{"opt": "not an int"}""".stripMargin)

Extraction.extract[OptionOfInt](obj) must throwA(
new MappingException(
"""
|No usable value for opt
|Do not know how to convert JString(not an int) into int
|""".stripMargin.trim))
}

"Extract should succeed for optional field with null value" in {
val obj = parse("""{"opt":null}""".stripMargin)
Extraction.extract[OptionOfInt](obj) must_== OptionOfInt(None)
}

"Extract should succeed for missing optional field" in {
val obj = parse("""{}""".stripMargin)
Extraction.extract[OptionOfInt](obj) must_== OptionOfInt(None)
}
}
}

0 comments on commit 9d609bb

Please sign in to comment.