Play framework: read Json containing null values
Asked Answered
K

1

5

I'm trying to read Json data in my Play Scala program. The Json may contain nulls in some fields, so this is how I defined the Reads object:

  implicit val readObj: Reads[ApplyRequest] = (
      (JsPath \ "a").read[String] and
      (JsPath \ "b").read[Option[String]] and
      (JsPath \ "c").read[Option[String]] and
      (JsPath \ "d").read[Option[Int]]
    )  (ApplyRequest.apply _) 

And the ApplyRequest case class:

case class ApplyRequest ( a: String,
                          b: Option[String],
                          c: Option[String],
                          d: Option[Int],
                          )

This does not compile, I get No Json deserializer found for type Option[String]. Try to implement an implicit Reads or Format for this type.

How to declare the Reads object to accept possible nulls?

Kathiekathleen answered 19/2, 2016 at 13:0 Comment(2)
do you use import play.api.libs.json._ ?Unheard
yes, that's the import I'm usingKathiekathleen
L
9

You can use readNullable to parse missing or null fields:

implicit val readObj: Reads[ApplyRequest] = (
  (JsPath \ "a").read[String] and
  (JsPath \ "b").readNullable[String] and
  (JsPath \ "c").readNullable[String] and
  (JsPath \ "d").readNullable[Int]
)  (ApplyRequest.apply _)
Lemmon answered 19/2, 2016 at 13:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.