2

I'm using Play 2 case class inception to translate to/from POSO (plain old scala object) and json strings.

on the toJson write transform, I want the empty POSO vals (Strings and Lists) to not even show up in the json string... howto do that?

Alan Jurgensen
  • 813
  • 11
  • 20

1 Answers1

2

You can add an implicit function omitEmpty quite easily.

implicit class RichJsObject(original: JsObject) {
  def omitEmpty: JsObject = original.value.foldLeft(original) { 
    case (obj, (key, JsString(st))) if st.isEmpty => obj - key
    case (obj, (key, JsArray(arr))) if arr.isEmpty => obj - key
    case (obj, (_, _)) => obj
  }
}

Then you can call omitEmpty on a JsObject.

scala> Json.obj("x" -> "", "y" -> JsArray()).omitEmpty
res5: play.api.libs.json.JsObject = {}
Ryan
  • 7,227
  • 5
  • 29
  • 40
  • Hey that works good when I implicitly create a JsObject ... but not sure howto use it via the inception via Json.toJson(POSO). – Alan Jurgensen Feb 15 '14 at 18:10
  • Define it on JsValue and use pattern-matching to avoid transforming non-JsObject JsValue instances. – Ryan Feb 16 '14 at 03:22