Last active
November 29, 2016 20:52
-
-
Save farmdawgnation/5236c5214b1db1d3955f1810b225dc78 to your computer and use it in GitHub Desktop.
This file contains 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 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