Skip to content

Instantly share code, notes, and snippets.

@meiwin
Created November 9, 2012 06:07
Show Gist options
  • Save meiwin/4043998 to your computer and use it in GitHub Desktop.
Save meiwin/4043998 to your computer and use it in GitHub Desktop.
Jerkson custom serializer/deserializer
import com.codahale.jerkson.Json
import org.codehaus.jackson.map.module.SimpleModule
import org.codehaus.jackson.{JsonParser, JsonGenerator, Version}
import org.codehaus.jackson.map.annotate.JsonCachable
import org.codehaus.jackson.map.{DeserializationContext, JsonDeserializer, SerializerProvider, JsonSerializer}
object CustomJson extends Json {
val module = new SimpleModule("CustomJson", Version.unknownVersion())
// --- (SERIALIZERS) ---
module.addSerializer(classOf[Enumeration#Value], new JerksonEnumerationSerializer())
// --- (DESERIALIZERS) ---
module.addDeserializer(classOf[UserType], new JerksonEnumerationDeserializer[UserType](UserTypes))
mapper.registerModule(module)
}
@JsonCachable
class JerksonEnumerationSerializer extends JsonSerializer[Enumeration#Value] {
override def serialize(id: Enumeration#Value, json: JsonGenerator, provider: SerializerProvider) {
json.writeString(id.toString)
}
}
@JsonCachable
class JerksonEnumerationDeserializer[T <: Enumeration#Value](enum: Enumeration) extends JsonDeserializer[T] {
override def deserialize(jp: JsonParser, context: DeserializationContext): T = {
return fetchEnumValue(jp.getText)
}
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