【问题标题】:Remove json field (when empty value) in serialize with json4s使用 json4s 序列化中删除 json 字段(当为空值时)
【发布时间】:2016-10-19 10:30:49
【问题描述】:

使用 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"} """

【问题讨论】:

  • 提示 - 编写一些代码肯定会有帮助。

标签: json scala json4s


【解决方案1】:
  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, ""))

【讨论】:

    猜你喜欢
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    相关资源
    最近更新 更多