gpt4 book ai didi

scala - 带有无序字段的 Json4s 自定义序列化程序

转载 作者:行者123 更新时间:2023-12-04 14:44:41 27 4
gpt4 key购买 nike

在 json4s 自述文件中给出的示例中 https://github.com/json4s/json4s#serializing-non-supported-types匹配仅在字段顺序为 {"start":0,"end":0} 时才有效。如果交换了开始和结束字段,则匹配不起作用。无论如何要编写以下案例匹配,以便 JSON 字段排序无关紧要?

case JObject(JField("start", JInt(s)) :: JField("end", JInt(e)) :: Nil)

最佳答案

我没有使用过这个库,所以我不确定这是否是正确的方法:(我花了几分钟查看文档后想出了这个)

class IntervalSerializer extends CustomSerializer[Interval](format => (
{
case x: JObject =>
x.obj.sortBy { case (k,_) => k } match {
case JField("end", JInt(e)) :: JField("start", JInt(s)) :: Nil =>
new Interval(start = s.longValue(), end = e.longValue())
}
},
{
case x: Interval =>
JObject(JField("start", JInt(BigInt(x.startTime))) ::
JField("end", JInt(BigInt(x.endTime))) :: Nil)
}
))

这个想法是按字母顺序对字段进行排序,然后创建 Interval 类。

关于scala - 带有无序字段的 Json4s 自定义序列化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24943710/

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