scala - Json4s 支持带有特征混合的案例类

标签 scala json4s

我正在尝试使用支持 jackson 的 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)

如果您对此问题有任何见解,我们将不胜感激。提前致谢

最佳答案

要使 Json4s 序列化的不仅仅是 case 类成员变量,您需要为您的特征添加一个 FieldSerializer 到您的 formats 变量,如下所示:

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

关于scala - Json4s 支持带有特征混合的案例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22179915/

相关文章:

scala - 将 CSV 从本地机器加载到在 Docker 上运行的 spark

scala - 类对象继承/协变

scala - json4s 总是转义 unicode 字符 €

scala - 将对象添加到以这些对象的成员为键的映射中

eclipse - 使用 SBT 和 Scala IDE 添加和删除依赖项

json - 使用 scala 提取嵌套的 JSON 元素

json4s - json4s中是否有针对UUID的开箱即用的(反)序列化器?

scala -- 如何使用 json4s 使用 SimpleDateFormat 自定义日期格式

scala - 如何编写处理集合的 json4s CustomSerializer

scala - 运行 Typesafe Console/Atmos 来监控 actor 系统/scala 应用程序。从 IntelliJ IDEA 或任何其他 IDE 运行