Play json - read null string as empty for Iterable[Array[String]]

570 views
Skip to first unread message

Nir

unread,
Apr 17, 2018, 3:09:04 PM4/17/18
to Play Framework [deprecated]
Basic issue is how to unmarshal Null string as empty. 

I see that play json has now few method to handle this situation:

readWithDefault[T](defaultValue: ⇒ T)(implicit r: Reads[T]): Reads[T]
Reads a T at JsPath

This works for String field as I can say in my read definition - (JsPath \ "datatype").readWithDefault[String]("")

But what about List and Map fields. e.g. I have result field with type Iterable[Array[String]]. How can I tell play json that treat any String value inside that Array inside Iterable as Empty?

Iterable[Array[Option[String]]] is not a good option as I will be iterating over this collection just to remove Option. This data is directly send over to client and I would like to avoid unnecessary iteration on big collection.

Thanks

Nir

unread,
Apr 17, 2018, 5:00:35 PM4/17/18
to Play Framework [deprecated]

I extended following reads to solve this:


  implicit object myStringReads extends Reads[String] {

      override def reads(json: JsValue) = {

        json match {

          case JsNull => JsSuccess("")

          case JsString(s) => JsSuccess(s)

          case _ => JsError(Seq(JsPath -> Seq(JsonValidationError("error.expected.jsstring"))))

Reply all
Reply to author
Forward
0 new messages