Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Scala Json Missing Property vs Null

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?

like image 571
James Cowhen Avatar asked Aug 22 '13 17:08

James Cowhen


1 Answers

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)
like image 180
trevor.reznik Avatar answered Sep 21 '22 19:09

trevor.reznik