gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:52:07 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com