Scala Json4s CustomKeySerializer

Scala Json4s CustomKeySerializer

在序列化 case class 时,我试图使 json 对象中的所有键都格式化为 PascalCase。看起来正确的方法是从 org.json4s 包中定义一个 CustomKeySerializer 并按照我的意愿重新格式化键。但是,虽然我能够让 CustomSerializer 工作,但我无法让 CustomKeySerializer 在序列化案例 class 时实际使用(嵌套案例 classes 未知类型)。我的代码如下所示:

case object PascalCaseSerializer extends CustomKeySerializer[String](format => (
  { case _ => "this is the deserializer and I don't need it" },
  { case _ => "this does nothing" }
))
implicit val formats: Formats = DefaultFormats + PascalCaseSerializer

case class Foo(thingId: Int, eventData: Any)
case class Bar(numThings: Int)
val event = Foo(1, Bar(2))

val payloadJson = write(event) // """{"thingId":1,"eventData":{"numThings":2}}"""

我在这里错过了什么?

看来您将不得不使用 CustomSerializer。如果您在 internalDecomposeWithBuilder 查看 Extraction.scala 源代码,您可能会注意到一段代码如下所示:

    while(iter.hasNext) {
      iter.next() match {
        case (k: String, v) => addField(k, v, obj)
        case (k: Symbol, v) => addField(k.name, v, obj)

        ...

        case (k, v) => {
          val customKeySerializer = formats.customKeySerializer(formats)
          if(customKeySerializer.isDefinedAt(k)) {
            addField(customKeySerializer(k), v, obj)
          } else {
            fail("Do not know how to serialize key of type " + k.getClass + ". " +
              "Consider implementing a CustomKeySerializer.")
          }
        }
      }
    }

这意味着您不能使用 CustomKeySerializer[String] 覆盖 String 键的默认行为。您只能使用 CustomKeySerializer 为未在此模式匹配中明确定义的键类型添加一些行为。