Serialize and Deserialize scala enumerations or case objects using json4s
Asked Answered
S

1

9

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

or

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

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)
  }
}
Sora answered 27/6, 2014 at 1:17 Comment(0)
F
24

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

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)
    }
  )
)
Foxhound answered 29/7, 2014 at 3:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.