Serializing and deserializing scala enumerations or object objects using json4s

Suppose I have an enumerated or private group of case objects:

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 } 

Which is the easiest way to create json formats for them, so that I can very easily (programmatically) generate json formats for use in a custom JsonFormat factory method, like the following, which works for all normal cases, classes, strings, collections, etc. .d, but returns {} or {"name": null} for the two enumerations listed above ?:

 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) } } 
+7
scala json4s
source share
1 answer

We used org.json4s.ext.EnumNameSerializer to serialize enums:

 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 a mixin property that adds an implicit format and defines all of our custom serializers / deserializers:

 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) } ) ) 
+18
source share

All Articles