Skip to content

Instantly share code, notes, and snippets.

@d6y
Created August 20, 2014 13:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d6y/eda9d968e78943e672ce to your computer and use it in GitHub Desktop.
Save d6y/eda9d968e78943e672ce to your computer and use it in GitHub Desktop.
Filtering out null JSON fields
import play.api.libs.json._
object Example extends App {
case class EmailPerformanceInfo(campaignCount: Int, name: Option[String])
implicit val emailPerformanceInfoWrites = new Writes[EmailPerformanceInfo] {
def writes(info: EmailPerformanceInfo): JsValue = {
import info._
Json.obj(
"campaignCount" -> campaignCount,
"fancyName" -> name // NB: this may turn into null in the JSON
)
}
}
// Remove null values from JSON (could pimp onto JsValue if you wanted)
def withoutNull(json: JsValue): JsValue = json match {
case JsObject(fields) =>
JsObject(fields.flatMap {
case (_, JsNull) => None // could match on specific field name here
case other @ (name,value) => Some(other) // consider recursing on the value for nested objects
})
case other => other
}
val withName = EmailPerformanceInfo(1, Some("Bob"))
val noName = EmailPerformanceInfo(100, None )
println(withoutNull(Json.toJson(withName)))
// -> {"campaignCount":1,"fancyName":"Bob"}
println(withoutNull(Json.toJson(noName)))
// -> {"campaignCount":100}
// What we really want is nullable handling in Json.obj:
// https://groups.google.com/forum/#!topic/play-framework-dev/o3ElehlHafM
// https://groups.google.com/d/msg/play-framework/J6nAAVJKXIE/r4XXNtty2McJ
}
@wuservices
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment