使用 json4s 序列化和反序列化 Scala 枚举或 case 对象

编程入门 行业动态 更新时间:2024-10-15 04:27:32
本文介绍了使用 json4s 序列化和反序列化 Scala 枚举或 case 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个枚举或密封的 case 对象组,如下所示:

Suppose I have an enumeration or sealed group of case objects as follows:

sealed abstract class Status case object Complete extends Status case object Failed extends Status case object Pending extends Status case object Unknown extends Status

object Status extends Enumeration { val Complete, Failed, Pending, Unknown = Value }

为这些创建 json 格式的最简单方法是什么,以便我可以非常轻松地(以编程方式)生成用于自定义 JsonFormat 工厂方法的 json 格式,如下所示,适用于所有正常的 case 类、字符串、集合等,但为上述两种类型的枚举生成 {} 或 {"name": null} ?:

What is the easiest way to create json formats for these so that I can very easily (programmatically) generate json formats for use in a custom JsonFormat factory method, such as the following, which works for all normal case classes, strings, collections, etc., but produces {} or {"name": null} for the above two types of enumerations?:

import org.json4s.DefaultFormats import org.json4s.jackson.JsonMethods.parse import org.json4s.jackson.Serialization import org.json4s.jvalue2extractable import org.json4s.string2JsonInput trait JsonFormat[T] { def read(json: String): T def write(t: T): String } object JsonFormat { implicit lazy val formats = DefaultFormats def create[T <: AnyRef: Manifest](): JsonFormat[T] = new JsonFormat[T] { def read(json: String): T = parse(json).extract[T] def write(t: T): String = Serialization.write(t) } }

推荐答案

我们使用了 org.json4s.ext.EnumNameSerializer 来序列化枚举:

We've used org.json4s.ext.EnumNameSerializer to serialize enumerations:

import org.json4s._ import org.json4s.ext.EnumNameSerializer class DoesSomething { implicit lazy val formats = DefaultFormats + new EnumNameSerializer(Status) ...stuff requiring serialization or deserialization... }

在实践中,我们有 mixin trait,它添加了隐式格式并定义了我们所有的自定义序列化器/反序列化器:

In practice we have mixin trait that adds the implicit format and defines all of our custom serializer/desrializers:

trait OurFormaters extends Json4sJacksonSupport { implicit lazy val json4sJacksonFormats:Formats = DefaultFormats + UuidSerializer + new EnumNameSerializer(Status) + ... } object UuidSerializer extends CustomSerializer[UUID](format => ( { case JString(s) => UUID.fromString(s) case JNull => null }, { case x: UUID => JString(x.toString) } ) )

更多推荐

使用 json4s 序列化和反序列化 Scala 枚举或 case 对象

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

发布评论

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

>www.elefans.com

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