使用 json4s 序列化和反序列化 Scala 枚举或 case 对象 [英] Serialize and Deserialize scala enumerations or case objects using json4s

查看:78
本文介绍了使用 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 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆