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



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

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

我们已经使用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 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)
    }
  )
)

相关内容

  • 没有找到相关文章

最新更新