我正在尝试读取 JSON 文件,例如:
{
"a": "abc",
"data" : {
"type" : 1,
...
}
}
其中 ... 部分可根据以下类型替换:
{
"a": "abc",
"data" : {
"type" : 1,
"b" : "bcd"
}
}
或者:
{
"a": "abc",
"data" : {
"type" : 2,
"c" : "cde",
"d" : "def",
}
}
对于我的一生,我无法找出正确的 JAXB 注释/类来实现这一点。如果需要,将类型变量移到数据块之外我没有问题。
我正在使用 Glassfish 3.1.2.2。
编辑:
根据 Perception 提供的代码,我做了一个快速的尝试……但在 glassfish 中不起作用:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = As.PROPERTY, property = "type")
@JsonSubTypes(
{
@JsonSubTypes.Type(value = DataSubA.class, name = "1"),
@JsonSubTypes.Type(value = DataSubB.class, name = "2")
})
@XmlRootElement
public abstract class Data implements Serializable
{
private static final long serialVersionUID = 1L;
public Data()
{
super();
}
}
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class DataSubA
extends Data
{
private static final long serialVersionUID = 1L;
@XmlElement
private BigDecimal expenditure;
public DataSubA() {
super();
}
public DataSubA(final BigDecimal expenditure) {
super();
this.expenditure = expenditure;
}
@Override
public String toString() {
return String.format("%s[expenditure = %s]\n",
getClass().getSimpleName(), getExpenditure());
}
public BigDecimal getExpenditure() {
return expenditure;
}
public void setExpenditure(BigDecimal expenditure) {
this.expenditure = expenditure;
}
}
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class DataSubB
extends Data
{
private static final long serialVersionUID = 1L;
@XmlElement
private String name;
@XmlElement
private Integer age;
public DataSubB()
{
super();
}
public DataSubB(final String name, final Integer age)
{
super();
this.name = name;
this.age = age;
}
@Override
public String toString()
{
return String.format("%s[name = %s, age = %s]\n",
getClass().getSimpleName(), getName(), getAge());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class DataWrapper
{
@XmlElement
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
还有一个简单的 POST 将其纳入:
@Stateless
@Path("x")
public class Endpoint
{
@POST
@Consumes(
{
MediaType.APPLICATION_JSON,
})
@Produces(
{
MediaType.APPLICATION_JSON,
})
public String foo(final DataWrapper wrapper)
{
return ("yay");
}
}
当我像这样传入 JSON 时:
{
"data" :
{
"type" : 1,
"expenditure" : 1
}
}
我收到如下消息:
Can not construct instance of Data, problem: abstract types can only be instantiated with additional type information
at [Source: org.apache.catalina.connector.CoyoteInputStream@28b92ec1; line: 2, column: 5] (through reference chain: DataWrapper["data"])