我正在尝试使用以下POJO测试MOXY:
公司:
@XmlRootElement(name="company")
@XmlSeeAlso({Computer.class, DesktopComputer.class, LaptopComputer.class})
@XmlAccessorType(XmlAccessType.FIELD)
public class Company {
@XmlElementWrapper(name = "computers")
@XmlElements({
@XmlElement(type = DesktopComputer.class, name = "desktop"),
@XmlElement(type = LaptopComputer.class, name = "laptop")
})
private List<Computer> computers;
public Company() {
computers = new ArrayList<Computer>();
}
public List<Computer> getComputers() {
return computers;
}
public void setComputers(List<Computer> computers) {
this.computers = computers;
}
public Company addComputer(? extends Computer computer) {
if ( computers == null ) {
computers = new ArrayList<Computer>();
}
computers.add(computer);
return this;
}
}
计算机:
@XmlSeeAlso({ LaptopComputer.class, DesktopComputer.class })
@XmlAccessorType(XmlAccessType.FIELD)
public class Computer {
@XmlAttribute
@XmlID
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
DesktopComputer:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "desktop")
public class DesktopComputer extends Computer {
@XmlElement(name = "location")
private String location;
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
LaptopComputer:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "laptop")
public class LaptopComputer extends Computer {
@XmlElement(name = "vendor")
private String vendor;
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
}
在XML中,这一切都按预期工作,我得到以下输出:
<?xml version="1.0" encoding="UTF-8"?>
<company>
<computers>
<desktop id="computer-1">
<location>Bangkok</location>
</desktop>
<desktop id="computer-2">
<location>Pattaya</location>
</desktop>
<laptop id="computer-3">
<vendor>Apple</vendor>
</laptop>
</computers>
</company>
在JSON中,我得到每个子类型的内部数组:
{
"company" : {
"computers" : {
"desktop" : [ {
"id" : "computer-1",
"location" : "Bangkok"
}, {
"id" : "computer-2",
"location" : "Pattaya"
} ],
"laptop" : [ {
"id" : "computer-3",
"vendor" : "Apple"
} ]
}
}
}
如何消除内部数组以获得以下JSON输出?
{
"company" : {
"computers" : {
"desktop" : {
"id" : "computer-1",
"location" : "Bangkok"
},
"desktop": {
"id" : "computer-2",
"location" : "Pattaya"
},
"laptop" : {
"id" : "computer-3",
"vendor" : "Apple"
}
}
}
}