Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize and Deserialize scala enumerations or case objects using json4s

Tags:

scala

json4s

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)
  }
}
like image 271
jonderry Avatar asked Jun 27 '14 01:06

jonderry


1 Answers

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)
    }
  )
)
like image 96
Symphony Avatar answered Oct 14 '22 10:10

Symphony