使用json4s序列化和反序列化scala枚举或案例对象

时间:2014-06-27 01:17:16

标签: scala json4s

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

  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格式的最简单方法是什么,以便我可以非常轻松地(以编程方式)生成json格式,以便在自定义JsonFormat工厂方法中使用,如下所示,适用于所有正常情况类,字符串,集合等,但对于上述两种类型的枚举产生{}{"name": null}?:

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)
  }
}

1 个答案:

答案 0 :(得分:20)

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

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,它添加了隐式格式并定义了所有自定义序列化器/解析器:

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)
    }
  )
)