Skip to content

Instantly share code, notes, and snippets.

@ryu1kn
Last active August 3, 2021 13:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryu1kn/374d886e8751da9d503b1a8d3443862f to your computer and use it in GitHub Desktop.
Save ryu1kn/374d886e8751da9d503b1a8d3443862f to your computer and use it in GitHub Desktop.
spray-json. Remove empty string before deserialising JSON
import org.scalatest.{Matchers, WordSpec}
import spray.json._
object JsonHelper {
implicit class JsObjectWrap(obj: JsObject) {
def removeEmptyValues: JsObject = JsObject(obj.fields
.map {
case (key, value: JsObject) => (key, value.removeEmptyValues)
case nonJsObject => nonJsObject
}
.filterNot {
case (_, value) => isEmptyValue(value)
}
)
private def isEmptyValue(value: JsValue): Boolean =
value == JsString("") || value == JsObject.empty
}
}
class JsonSpec extends WordSpec with Matchers {
import JsonHelper._
"JsObject" should {
"drop empty strings" in {
val json = """{"p1":"","p2":"value","p3":""}""".parseJson.asJsObject
json.removeEmptyValues shouldEqual """{"p2":"value"}""".parseJson
}
"drop empty objects" in {
val json = """{"p1":"value","p2":{}, "p3":{}}""".parseJson.asJsObject
json.removeEmptyValues shouldEqual """{"p1":"value"}""".parseJson
}
"drop an empty string in a nested object" in {
val json = """{"p1":{"p2":"value","p3":""}}""".parseJson.asJsObject
json.removeEmptyValues shouldEqual """{"p1":{"p2":"value"}}""".parseJson
}
"drop an object that contains only empty strings" in {
val json = """{"p1":"value","p2":{"p3":"","p4":""}}""".parseJson.asJsObject
json.removeEmptyValues shouldEqual """{"p1":"value"}""".parseJson
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment