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

编程入门 行业动态 更新时间:2024-10-14 06:25:02
本文介绍了Json4s 支持带有特征混合的案例类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用 json4s 和 jackson 支持序列化 scala case 类.但是对于我尝试混合特征的场景,它无法序列化类.下面是一个代码示例.

trait ISearchKey {var id:String = ""}

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

val fld = new CrystalFieldInfo("Field1") with ISearchKeyfld.id = "Id1"隐式 val 格式 = Serialization.formats(NoTypeHints)val ser = write[CrystalFieldInfo with ISearchKey](fld)打印(系列)

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

解决方案

为了让 Json4s 序列化的不仅仅是 case 类成员变量,你需要为你的 trait 添加一个 FieldSerializer 到你的格式变量,像这样:

隐式 val 格式 = DefaultFormats + FieldSerializer[ISearchKey]()val ser = write[CrystalFieldInfo with ISearchKey]println(ser)//应该包含 ISearchKey trait 中的id"字段

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

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

I am trying to serialize scala case class using json4s with jackson support. But for scenarios where i am trying to mixin traits, it fails to serialize the class. Below is a code example.

trait ISearchKey { var id:String = "" }

When i execute below code i get empty curly brackets, no value serialized, but if i remove trait mixin then CrystalFieldInfo value gets serialized properly

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)

Would appreciate any insight into this problem. Thanks in advance

解决方案

To make Json4s serialize more than just case class member variables, you need to add a FieldSerializer for your trait to your formats variable, like so:

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

More info on FieldSerializers here: github/json4s/json4s#serializing-fields-of-a-class

There are also several examples in the source: github/json4s/json4s/blob/ebc76d70309c79c39df4be65f16b88d208f47055/tests/src/test/scala/org/json4s/native/FieldSerializerExamples.scala

更多推荐

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

本文发布于:2023-07-14 14:47:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1105108.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:特征   案例   Json4s

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!