【问题标题】:Scala Json4s CustomKeySerializerScala Json4s CustomKeySerializer
【发布时间】:2017-10-26 21:36:58
【问题描述】:

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

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

我在这里错过了什么?

【问题讨论】:

    标签: json scala json4s json-serialization


    【解决方案1】:

    看来您必须使用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 为该模式匹配中未明确定义的键类型添加一些行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2015-09-17
      相关资源
      最近更新 更多