Jackson Scala JSON序列化/反序列化元组

时间:2015-01-02 01:12:02

标签: json scala serialization jackson tuples

下面我只是尝试使用jackson-module-scala进行Tuple2的往返。使用Scala 2.10.4。为什么它不起作用?

可以看出,串行器选择将Tuple2编码为JSON数组。为什么解串器不能将JSON数组解码回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)

1 个答案:

答案 0 :(得分:1)

查看DeserializerTest特征,好像您需要将TypeReference传递给readValue方法。这应该有效:

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