鉴于这个简单的示例,第三个测试“反序列化”失败并显示消息。
Can not construct instance of com.egc.ost.pricing.contracts.response.A, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
at [Source: java.io.StringReader@1f03691; line: 2, column: 29]
com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.egc.ost.pricing.contracts.response.A, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
at [Source: java.io.StringReader@1f03691; line: 2, column: 29]
即使第二个测试“de-serialize_a”证明杰克逊可以解析正确的多态类型。
我正在使用杰克逊版本和 scala 模块
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-scala_2.10</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>2.2.2</version>
</dependency>
代码:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "type")
@JsonSubTypes(Array(
new Type(value = classOf[B], name = "B"),
new Type(value = classOf[C], name = "C")))
trait A{}
case class B(value : Double) extends A
case class C(value : String) extends A
case class Owner( results: Seq[(String, A)])
class ATest extends FlatSpec with ShouldMatchers {
behavior of "A"
it should "serialise" in {
val owner : Owner = Owner(Seq(("ExampleB",B(1.0)),("ExampleC",C("One"))))
val serialize: String = JsonMarshall.serialize(owner)
println(serialize)
}
it should "de-serialize_a" in {
val a: A = JsonMarshall.deserialize[A]("""{
| "type" : "C",
| "value" : "One"
| }""".stripMargin)
println(a)
}
val json = """{
| "results" : [ [ "ExampleB", {
| "type" : "B",
| "value" : 1.0
| } ], [ "ExampleC", {
| "type" : "C",
| "value" : "One"
| } ] ]
|}""".stripMargin
it should "de-serialize" in {
val owner: Owner = JsonMarshall.deserialize[Owner](json)
println(owner)
}
}