It is straightforward to read the expected fields (no matter optional or not) and validate them, but I fail on how to throw an exception properly if an unexpected field is detected in the given json. It'd be great if the play framework could help on it with one or two statements. Yes, I can process the json and get all the fields' names and compare them to the expected list, which appears to be a bit complicated (when the json input's format is complicated).
For example, the input json is expected as following:
{
"param": 1,
"period": 2,
"threshold": 3,
"toggle": true
}
and the scala code to fultill the class EventConfig from the json input:
import play.api.libs.json._
import play.api.libs.functional.syntax._
case class EventConfig(param: Int, period: Int, threshold: Int, toggle: Boolean)
object EventConfig {
implicit val jsonReads: Reads[EventConfig] = (
(__ \ "param").read[Int] and
(__ \ "period").read[Int] and
(__ \ "threshold").read[Int] and
(__ \ "toggle").read[Boolean]
)(EventConfig.apply _)
}
I'd like to have an exception thrown if an unexpected filed is detected in the json such as
{
"param": 1,
"period": 2,
"threshold": 3,
"toggle": true,
"foo": "bar"
}
Reads
would just ignore thefoo
field. – Michael Zajac