Skip to content

Instantly share code, notes, and snippets.

@farmdawgnation
Last active November 29, 2016 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save farmdawgnation/5236c5214b1db1d3955f1810b225dc78 to your computer and use it in GitHub Desktop.
Save farmdawgnation/5236c5214b1db1d3955f1810b225dc78 to your computer and use it in GitHub Desktop.
import scala.collection._
import org.json4s._
object SingletonSerializer extends Serializer[Any] {
private[this] var memoizedSingletons: mutable.Map[(Class[_], String), Any] = mutable.Map.empty
private def isValidSingleton(clazz: Class[_], classIdentifier: String) = {
if (memoizedSingletons.contains((clazz, classIdentifier))) {
true
} else if (classIdentifier.endsWith("$")) {
val singlesonClass = Class.forName(classIdentifier)
clazz.isAssignableFrom(singlesonClass)
} else {
false
}
}
def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), Any] = {
case (TypeInfo(clazz, _), json) if json.extractOpt[String].map(isValidSingleton(clazz, _)).getOrElse(false) =>
memoizedSingletons.getOrElseUpdate((clazz, json.extract[String]), {
val className = json.extract[String]
Class.forName(className).getField("MODULE$").get()
})
}
def serialize(implicit format: Formats) = {
case possibleSingleton if possibleSingleton.getClass.getName().endsWith("$") =>
JString(possibleSingleton.getClass.getName())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment