Skip to content

Instantly share code, notes, and snippets.

@casualjim
Last active June 16, 2022 02:20
Show Gist options
  • Save casualjim/5130756 to your computer and use it in GitHub Desktop.
Save casualjim/5130756 to your computer and use it in GitHub Desktop.
A simple example of a custom serializer for json4s
import org.json4s._
case class MyClass(id: Int) {
lazy val blah = "lazy string"
}
class MyClassSerializer extends Serializer[MyClass] {
private val MyClassClass = classOf[MyClass]
def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), MyClass] = {
case (TypeInfo(MyClassClass, _), json) => json match {
case JObject(JField("id", JInt(id)) :: _) =>
MyClass(id)
case x => throw new MappingException("Can't convert " + x + " to MyClass")
}
}
def serialize(implicit formats: Formats): PartialFunction[Any, JValue] = {
case x: MyClass =>
import JsonDSL._
("id" -> x.id) ~ ("blah" -> x.blah)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment