Skip to content

Instantly share code, notes, and snippets.

@d6y
Created Aug 20, 2014
Embed
What would you like to do?
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

wuservices commented May 19, 2017

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