Reputation: 2955
I have a use case where I need to accept null values, but not missing properties. This is on Play Framework 2.1.3
For example:
case class Foo(a: Option[String], b: Option[String], c: Option[String])
This case class could be part of a larger case class
I would like to accept the following and generate the foo object:
{
"foo" : {
"a" : "blah",
"b" : null,
"c" : "blah"
}
}
But not this:
{
"foo" : {
"a" : "blah",
"c" : "blah"
}
}
Currently I have the following to read the JSON into the case class:
val FooReader = (
(__ \ "a").readNullable[Setting] and
(__ \ "b").readNullable[String] and
(__ \ "c").readNullable[String])(Foo)
How can I make FooReader generate JsError on missing property but allow null?
Upvotes: 4
Views: 3008
Reputation: 286
You can use something like :
val FooReader = (
(__ \ "a").readNullable[String] and
(__ \ "b").read(Reads.optionNoError[String]) and
(__ \ "c").readNullable[String]
)(Foo)
The 'Reads.optionNoError[String]' will produce a JsError if '(__ \ "b")' is missing.
You can actually do something like :
val FooReader = (
(__ \ "a").read(Reads.optionNoError[String]) and
(__ \ "b").read(Reads.optionNoError[String]) and
(__ \ "c").read(Reads.optionNoError[String])
)(Foo)
Upvotes: 4