在序列化PascalCase时,我试图使json对象中的所有键都格式化为case class。看起来,正确的方法是从CustomKeySerializer包中定义一个org.json4s,并按照我的意愿重新格式化键。但是,虽然我能够让一个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}}"""我在这里错过了什么?
发布于 2017-10-26 23:08:25
看起来您将不得不使用CustomSerializer。如果您查看Extraction.scala源代码在internalDecomposeWithBuilder,您可能会注意到一段代码如下:
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为在此模式匹配中未显式定义的键类型添加一些行为。
https://stackoverflow.com/questions/46964228
复制相似问题