使用json4s序列化删除json字段(空值时)的最佳做法是什么?
val json = ("foo" -> "bar") ~ ("fizz" -> "buzz")
compact(render(json))
""" {"foo":"bar","fizz":"buzz"} """
val json = ("foo" -> "bar") ~ ("fizz" -> "")
compact(render(json))
""" {"foo":"bar"} """
答案 0 :(得分:0)
val formats = DefaultFormats.withEmptyValueStrategy(new EmptyValueStrategy {
def noneValReplacement = None
def replaceEmpty(value: JValue): JValue = {
case JString("") => JNothing
case JArray(items) => JArray(items map replaceEmpty)
case JObject(fields) => JObject(fields map {
case JField(name, v) => JField(name, replaceEmpty(v))
})
case oth => oth
}
})
compact(render(("foo" -> "bar") ~ ("fizz" -> "")))
val customSerializer = new CustomSerializer[String](_ => ({ case JString(s) => s }, { case "" => JNothing case s: String => JString(s) }))
implicit val jsonFormat = DefaultFormats + customSeirializer
case class Foo(a: Int, b: String)
Serialization.write(Foo(42, ""))