繁体   English   中英

在使用json4s序列化时删除json字段(当为空值时)

[英]Remove json field (when empty value) in serialize with json4s

使用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"} """
  1. 使用EmptyValueStrategy(如果您序列化JValue)
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" -> "")))
  1. 使用CustomSerializer(如果要序列化案例类)
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, ""))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM