Last active
August 3, 2021 13:38
-
-
Save ryu1kn/374d886e8751da9d503b1a8d3443862f to your computer and use it in GitHub Desktop.
spray-json. Remove empty string before deserialising JSON
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 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