Skip to content

Instantly share code, notes, and snippets.

@crimsoncor
Created August 3, 2012 05:32
Show Gist options
  • Save crimsoncor/3244718 to your computer and use it in GitHub Desktop.
Save crimsoncor/3244718 to your computer and use it in GitHub Desktop.
A more up-to-date example of how map key serialization in jackson does not work.
package test
import scala.collection.{immutable => im}
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer
import com.fasterxml.jackson.databind.{ObjectMapper, DeserializationContext}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.annotation.JsonValue
object JacksonMapTest2 {
def main(args: Array[String]): Unit = {
val pair = new Pair(2, 3)
val map = im.HashMap(pair -> "Horsey")
val thingie = new Thingie(map)
val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)
val str = mapper.writeValueAsString(thingie)
println(str)
val result = mapper.readValue(str, classOf[Thingie])
result._1.foreach(e => println(e._1.getClass))
println(result)
}
}
class Pair(val arg1: Int, val arg2: Int)
extends Product2[Int, Int]
{
def _1 = arg1
def _2 = arg2
override def canEqual(that: Any): Boolean = that.isInstanceOf[Pair]
// override
// def toString(): String =
// {
// "{\"arg1\":%d,\"arg2\":%d}".format(arg1, arg2)
// }
}
object Pair
{
class PairKD
extends StdKeyDeserializer(classOf[Pair])
{
override
def _parse(key: String , ctxt: DeserializationContext): Pair =
{
val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)
try {
return mapper.readValue(key, classOf[Pair])
}
catch {
case ex: Exception => throw ctxt.weirdKeyException(_keyClass, key, ex.getMessage);
}
}
}
class PairKS
extends StdSerializer[Pair](classOf[Pair])
{
override
def serialize(value: Pair, jgen: JsonGenerator, provider: SerializerProvider)
{
val mapper = new ObjectMapper().registerModule(DefaultScalaModule)
jgen.writeFieldName(mapper.writeValueAsString(value));
}
}
}
class Thingie(
@JsonSerialize(keyUsing=classOf[test.Pair.PairKS])
@JsonDeserialize(keyUsing=classOf[test.Pair.PairKD])
val arg1: im.HashMap[Pair, String])
extends Product1[im.HashMap[Pair, String]]
{
def _1 = arg1
override def canEqual(that: Any): Boolean = that.isInstanceOf[Thingie]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment