Reputation: 253
I'm having some troubles parsing a JSON response with Play 2.1 parser. Say I receive the following json as a string:
{"name": "myName"}
I'm able to parse it using these few lines...
case class MyJsonObj(name: String)
implicit val jsonRead = (
(__ \ "name").read[String])(MyJsonObj.apply _)
val myObj = Json.parse("{\"name\": \"myName\"}").valide[MyJsonObj]
Now say I receive almost the same message but instead of having a string as "myName" I receive a null (i.e: {"name": null}), the parsing fails... Ideally, whenever I receive a null, I would like to put a default value (instead of raising an error) and keep parsing.
Any suggestions? Thanks!
Upvotes: 1
Views: 302
Reputation: 7877
You can achieve this with readNullable
or orElse
:
(__ \ 'name).readNullable[String].map(_.getOrElse("default"))
// Another solution:
(__ \ 'name).read[String] orElse Reads.pure("default")
Note: Readers don't work fine with "one-field" case class (but I suppose it's just for this example). Otherwise, see this topic.
Upvotes: 2