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

时间:2016-10-19 10:30:50

标签: json scala 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 个答案:

答案 0 :(得分:0)

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