Skip to content

Instantly share code, notes, and snippets.

@meiwin
Created October 24, 2012 08:18
Show Gist options
  • Save meiwin/3944779 to your computer and use it in GitHub Desktop.
Save meiwin/3944779 to your computer and use it in GitHub Desktop.
Lift JSON Scala serializer for Enumeration
import net.liftweb.json.JsonAST.{JObject, JField, JString, JValue}
import net.liftweb.json._
import net.liftweb.json.JsonAST.JField
import net.liftweb.json.JsonAST.JObject
import net.liftweb.json.JsonAST.JString
import net.liftweb.json.TypeInfo
import net.liftweb.json.MappingException
class EnumerationSerializer[T <: Enumeration#Value](enum: Enumeration, clazz: Class[T]) extends Serializer[T] {
import JsonDSL._
// def EnumerationClass[T] = classOf[T]
override def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), T] = {
case (TypeInfo(clazz, _), json) => json match {
case JObject(List(JField(name, JString(value)))) => fetchEnumValue(value)
case JString(value) => fetchEnumValue(value)
case value => throw new MappingException("Can't convert " + value + " to " + clazz)
}
}
override def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
case expected if clazz.isInstance(expected) => expected.toString
}
private def fetchEnumValue(value: String): T = {
enum.values.find(_.toString == value).getOrElse(throw new Exception("Invalid enum value => " + value)).asInstanceOf[T]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment