Skip to content

Instantly share code, notes, and snippets.

@francisdb
Created August 29, 2013 21:57
Show Gist options
  • Save francisdb/6383937 to your computer and use it in GitHub Desktop.
Save francisdb/6383937 to your computer and use it in GitHub Desktop.
JacksonMapper for easy json in scala
val fasterXmlJacksonVersion = "2.2.2"
val appDependencies = Seq(
"com.fasterxml.jackson.core" % "jackson-core" % fasterXmlJacksonVersion,
"com.fasterxml.jackson.core" % "jackson-annotations" % fasterXmlJacksonVersion,
"com.fasterxml.jackson.core" % "jackson-databind" % fasterXmlJacksonVersion,
"com.fasterxml.jackson.module" %% "jackson-module-scala" % fasterXmlJacksonVersion
)
import java.lang.reflect.{Type, ParameterizedType}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.core.`type`.TypeReference
import com.fasterxml.jackson.core.JsonParseException
@deprecated("Use the play json serialisation lib or maybe json4s", "20130829")
trait JacksonMapper {
private val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)
protected def deserialize[T: Manifest](value: String) : T = {
try{
mapper.readValue(value, new TypeReference[T]() {
override def getType = new ParameterizedType {
val getActualTypeArguments = manifest[T].typeArguments.map(_.runtimeClass.asInstanceOf[Type]).toArray
val getRawType = manifest[T].runtimeClass
val getOwnerType = null
}
})
}catch{
case ex:JsonParseException =>
System.err.println(value)
throw ex;
}
}
protected def serialize(value:AnyRef): String = {
mapper.writeValueAsString(value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment