Created
August 29, 2013 21:57
-
-
Save francisdb/6383937 to your computer and use it in GitHub Desktop.
JacksonMapper for easy json in scala
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
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 | |
) |
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 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