如何使用json4s将对象序列化为AST?

编程入门 行业动态 更新时间:2024-10-14 16:22:44
本文介绍了如何使用json4s将对象序列化为AST?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在编写一个客户序列化程序.在那个 Serializer 中,我想以某种方式说:这个东西你已经知道如何序列化了".

I am writing a Customer Serializer. In that Serializer I would like to somehow say: "and this thing you already know how to serialize".

我目前的方法是这样的:

My current approach looks like that:

import org.json4s.native.Serialization._ import org.json4s.JsonDSL.WithBigDecimal._ object WindowSerializer extends CustomSerializer[Window](format => ( [omitted], { case Window(frame, size) => ( "size" -> size ) ~ ( "frame" -> parse(write(frame)) ) }))

那个 parse(write(frame)) 事情既丑陋又低效.如何解决?

That parse(write(frame)) things is both ugly and inefficient. How to fix that?

推荐答案

你可以调用 Extraction.decompose(a: Any)(implicit format: Formats): JValue 产生一个 JValue 使用运行时反射从某个值中提取.

You can call Extraction.decompose(a: Any)(implicit formats: Formats): JValue which produces a JValue from some value using runtime reflection.

import org.json4s._ import org.json4s.jackson.JsonMethods._ import org.json4s.JsonDSL._ import java.util.UUID case class Thing(name: String) case class Box(id: String, thing: Thing) class BoxSerializer extends CustomSerializer[Box](format => ({ case jv: JValue => val id = (jv \ "id").extract[String] val thing = (jv \ "thing").extract[Thing] Box(id, thing) }, { case b: Box => ("token" -> UUID.randomUUID().toString()) ~ ("id" -> box.id) ~ ("thing" -> Extraction.decompose(box.thing)) })) implicit val formats = DefaultFormats + new BoxSerializer val box = Box("1000", Thing("a thing")) // decompose the value to JSON val json = Extraction.decompose(box) println(pretty(json)) // { // "token" : "d9bd49dc-11b4-4380-ab10-f6df005a384c", // "id" : "1000", // "thing" : { // "name" : "a thing" // } // } // and read a value of type Box back from the JSON println(json.extract[Box]) // Box(1000,Thing(a thing))

更多推荐

如何使用json4s将对象序列化为AST?

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

发布评论

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

>www.elefans.com

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