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?
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)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With