Created
August 20, 2014 13:17
-
-
Save d6y/eda9d968e78943e672ce to your computer and use it in GitHub Desktop.
Filtering out null JSON fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Similar solutions at http://stackoverflow.com/questions/24512942/play-how-to-remove-the-fields-without-value-from-json-and-create-a-new-json-wit. For just JsObject, filter is slightly simpler.