我目前正在尝试使用JAXB将一些复杂对象序列化为JSON。我使用Jersey作为REST框架,具有以下配置类:
@ApplicationPath("/customerManagement")
public class ApplicationConfiguration extends ResourceConfig {
public PartyLocationManagementApplication() {
register(MOXyJsonProvider.class);
}
}
我已经设置了以下类:
@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({
AbstractListRTO.class,
AbstractDataRTO.class
})
public class RestTransferObject {
private Link self;
public Link getSelf() {
return self;
}
public void setSelf(Link self) {
this.self = self;
}
}
@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({CustomersRTO.class})
public abstract class AbstractListRTO<T extends RestTransferObject>
extends RestTransferObject {
@XmlElement(name = "element")
private Collection<T> elements;
public Collection<T> getElements() {
return elements;
}
public void setElements(Collection<T> elements) {
this.elements = elements;
}
}
@XmlRootElement
@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
public class CustomersRTO extends AbstractListRTO<CustomerRTO> {
public CustomersRTO(Collection<CustomerRTO> customers) {
super.setElements(customers);
}
public CustomersRTO() {
}
public Collection<CustomerRTO> getCustomers() {
return getElements();
}
public void setCustomers(Collection<CustomerRTO> customers) {
setElements(customers);
}
}
@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({CustomerRTO.class})
public abstract class AbstractDataRTO extends RestTransferObject {
private Integer no;
public AbstractDataRTO() {
}
public Integer getNo() {
return no;
}
public void setNo(Integer no) {
this.no = no;
}
}
@XmlRootElement
@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
public class CustomerRTO extends AbstractDataRTO {
public CustomerRTO() {
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
目前我收到以下JSON输出:
{
"@type": "customersRTO",
"element": [
{
"@type": "abstractDataRTO",
"self": {
"href": "http://somelink/1"
},
"no": 1
},
{
"@type": "abstractDataRTO",
"self": {
"href": "http://somelink/1"
},
"no": 2
}
]
}
但我想要的是这样的:
{
"@type": "customersRTO",
"element": [
{
"@type": "customerRTO",
"self": {
"href": "http://somelink/1"
},
"no": 1,
"name": "Jon"
},
{
"@type": "customerRTO",
"self": {
"self": {
"href": "http://somelink/1"
},
"no": 2,
"name": "Jane"
}
]
}
可以看出,字段@type具有不同的值,字段名称丢失。我确保将CustomerRTO添加到customersRTO列表中。如果我请求xml表示,那么每件事都可以正常工作,但是一旦我尝试请求JSON表示,每件事都会出错。