Last active
June 16, 2022 02:20
-
-
Save casualjim/5130756 to your computer and use it in GitHub Desktop.
A simple example of a custom serializer for json4s
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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