【问题标题】:Json4s support for case class with trait mixinJson4s 支持带有 trait mixin 的案例类
【发布时间】:2014-03-04 18:24:12
【问题描述】:

我正在尝试使用支持杰克逊的 json4s 序列化 scala 案例类。但是对于我试图混合特征的场景,它无法序列化类。下面是一个代码示例。

trait ISearchKey {
    var id:String = ""  
}

当我执行下面的代码时,我得到空的大括号,没有序列化值,但是如果我删除 trait mixin,CrystalFieldInfo 值会被正确序列化

  val fld = new CrystalFieldInfo("Field1") with ISearchKey
  fld.id = "Id1"          
  implicit val formats = Serialization.formats(NoTypeHints)
  val ser = write[CrystalFieldInfo with ISearchKey](fld)
  println(ser)

不胜感激任何对此问题的见解。提前致谢

【问题讨论】:

  • 您不应该提供类型提示,因为在您将案例类与特征混合后会更改结果类型吗?
  • 你有想过这个吗?我遇到了同样的问题。

标签: scala json4s


【解决方案1】:

要使 Json4s 序列化不仅仅是案例类成员变量,您需要为您的 trait 添加一个 FieldSerializer 到您的格式变量,如下所示:

implicit val formats = DefaultFormats + FieldSerializer[ISearchKey]()
val ser = write[CrystalFieldInfo with ISearchKey]
println(ser) // should include the "id" field from the ISearchKey trait

更多关于 FieldSerializers 的信息在这里:https://github.com/json4s/json4s#serializing-fields-of-a-class

源码中也有几个例子:https://github.com/json4s/json4s/blob/ebc76d70309c79c39df4be65f16b88d208f47055/tests/src/test/scala/org/json4s/native/FieldSerializerExamples.scala

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 2015-05-18
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多