How to thrown an exception on missing fields?

3,162 views
Skip to first unread message

Volkan Yazıcı

unread,
Mar 13, 2014, 10:32:08 AM3/13/14
to jackso...@googlegroups.com
Hi,

While mapping an object from a JSON string (using "jackson-module-scala_2.10" % "2.3.1"), how can I make Jackson to thrown an exception for the missing fields? That is, consider the following code snippet.

import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import org.scalatest.FunSuite

class TickerResponse
(val low: Double,
val high: Double,
val last: Double,
val bid: Double,
val ask: Double,
val volume: Double,
val timestamp: Double)

class ResponseSuite extends FunSuite {

private val mapper = new ObjectMapper()
.registerModule(DefaultScalaModule)
.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true)
.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, true)
.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true)

test("TickerResponse deserialization should fail on bogus data") {
val json = """{"high":1418.73, "last":1402.28}"""
val res = mapper.readValue(json, classOf[TickerResponse])
println(f"res.ask: ${res.ask}")
}

}

Here, the test outputs "res.ask: 0.0", whereas, readValue() should have thrown an exception. Any ideas?

Best.

Tatu Saloranta

unread,
Mar 13, 2014, 11:53:59 AM3/13/14
to jackso...@googlegroups.com
Jackson does not support data validation (beyond simple detection of inconvertibility of structural values), and concept of missing values would fall into this category.
There are some work-arounds that could work: for example, when using constructor-based instantiaton (@JsonCreator), detect null argument (assuming explicit null is not allowed) and throw exception.

But more common way I think is to use something like Bean Validation API after data-binding, since it allows much more complicated validity checking.

-+ Tatu +-

Reply all
Reply to author
Forward
0 new messages