我有一个通过cxf的POST Rest服务,它接受一个JSON对象。它接受的类是一个抽象类和2个具体实现。
以下是我的代码:
TestService.java
@Path("/test")
@POST
@Consumes({MediaType.APPLICATION_JSON})
public Response test(TestEntity testEntity)
{
System.out.println(testEntity);
return Response.ok().build();
}
TestEntity.java
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = TestEntityA.class, name = "a"),
@JsonSubTypes.Type(value = TestEntityB.class, name = "b")
})
public abstract class TestEntity
{
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
TestEntityA.java
public class TestEntityA extends TestEntity
{
private String propertyA;
public String getPropertyA()
{
return propertyA;
}
public void setPropertyA(String propertyA)
{
this.propertyA = propertyA;
}
}
TestEntityB.java
public class TestEntityB
{
private String propertyB;
public String getPropertyB()
{
return propertyB;
}
public void setPropertyB(String propertyB)
{
this.propertyB = propertyB;
}
}
我从客户端传递的JSON对象如下:
{
"type": "a",
"name": "TestA",
"propertyA": "Property A"
}
这样我得 400 Bad Request 错误:
Can not construct instance of com.pb.spectrum.profiling.config.entities.TestEntity, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
at [Source: org.apache.cxf.transport.http.AbstractHTTPDestination$1@7967caad; line: 1, column: 1]
但是,当我在测试用例中使用对象映射器序列化/反序列化对象时,它可以正常工作
TestEntity testEntityA = new TestEntityA();
testEntityA.setName("TestA");
((TestEntityA)testEntityA).setPropertyA("Property A");
String json = objectMapper.writeValueAsString(testEntityA);
System.out.println(json);
//This outputs following:
{
"type": "a",
"name": "TestA",
"propertyA": "Property A"
}
TestEntity testEntity = objectMapper.readValue(json,TestEntity.class);
//testEntity is instance of TestEntityA.
System.out.println(testEntity);
由于cxf无法正确地取消json,可能会出现什么问题?