Michael Malak
Michael Malak

Reputation: 648

Jackson Scala JSON serialize/deserialize Tuple

Below I'm just trying to a round-trip of a Tuple2 using jackson-module-scala. Using Scala 2.10.4. Why doesn't it work?

As can be seen, the serializer opts to encode the Tuple2 as a JSON array. Why can't the deserializer decode the JSON array back into a Tuple2?

wget http://central.maven.org/maven2/com/fasterxml/jackson/module/jackson-module-scala_2.10/2.4.4/jackson-module-scala_2.10-2.4.4.jar
wget http://central.maven.org/maven2/com/google/guava/guava/15.0/guava-15.0.jar
wget http://central.maven.org/maven2/com/fasterxml/jackson/core/jackson-core/2.4.4/jackson-core-2.4.4.jar
wget http://central.maven.org/maven2/com/fasterxml/jackson/core/jackson-databind/2.4.4/jackson-databind-2.4.4.jar
wget http://central.maven.org/maven2/com/fasterxml/jackson/core/jackson-annotations/2.4.4/jackson-annotations-2.4.4.jar

scala -cp jackson-module-scala_2.10-2.4.4.jar:guava-15.0.jar:jackson-core-2.4.4.jar:jackson-databind-2.4.4.jar:jackson-annotations-2.4.4.jar

val mapper = new com.fasterxml.jackson.databind.ObjectMapper()
mapper.registerModule(com.fasterxml.jackson.module.scala.DefaultScalaModule)
val writer = new java.io.StringWriter()
mapper.writeValue(writer, (1,2))
mapper.readValue(writer.toString,classOf[Tuple2[Integer,Integer]])

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of scala.Tuple2 out of VALUE_NUMBER_INT token
    at [Source: [1,2]; line: 1, column: 2]
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
    at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:762)
    at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:758)
    at com.fasterxml.jackson.module.scala.deser.TupleDeserializer.deserialize(TupleDeserializerModule.scala:61)
    at com.fasterxml.jackson.module.scala.deser.TupleDeserializer.deserialize(TupleDeserializerModule.scala:15)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3066)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2161)

Upvotes: 0

Views: 2413

Answers (1)

edi
edi

Reputation: 3122

Looking at the DeserializerTest trait it seems as if you need to pass a TypeReference to the readValue method. This should work:

mapper.readValue[(Int,Int)](writer.toString, new TypeReference[(Int,Int)]{})

Upvotes: 1

Related Questions