[英]JAXB Marshall/Unmarshall a class object with List variable member
我正在嘗試使用JAXB加載一系列XML文件,以為每個類創建多個對象列表。
瓷磚類
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement//(name="Tiles")
@XmlAccessorType(XmlAccessType.FIELD)
public class Tile {
private String name;
public String getName(){
return name;
}
public void setName(String arg){
this.name = arg;
}
private int id;
public int getId() {
return id;
}
public void setId(int arg){
this.id = arg;
}
private String imageName;
public String getImageName(){
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
private int drawType;
public int getDrawType(){
return drawType;
}
public void setDrawType(int drawType) {
this.drawType = drawType;
}
private int trueType;
public int getTrueType() {
return trueType;
}
public void setTrueType(int trueType) {
this.trueType = trueType;
}
private int count;
public int getCount(){
return count;
}
public void setCount(int count) {
this.count = count;
}
private List<Integer> side;
public Integer getSide(int arg){
return side.get(arg);
}
public void setSide(List<Integer> side) {
this.side = side;
}
private int feature;
public int getFeature (){
return feature;
}
public void setFeature(int feature) {
this.feature = feature;
}
}
因此,當我真正嘗試解組XML時,我認為首先對一個類的測試實例進行組編以確認生成的XML文件的格式是個好主意。
JAXBContext jc = JAXBContext.newInstance(Tile.class,JAXB2_Lists.class,Feature.class );
JAXB2_Lists<Tile> exportTest = new JAXB2_Lists<>();
Marshaller marshaller = jc.createMarshaller();
Tile testTile = new Tile();
testTile.setCount(1);
testTile.setDrawType(1);
testTile.setFeature(1);
testTile.setId(1);
testTile.setImageName("TestImage.png");
testTile.setName("Test Name");
testTile.setTrueType(1);
List<Integer> sides = new ArrayList<>();
testTile.setSide(sides);
exportTest.getValues().add(testTile);
marshaller.marshal(exportTest, new File("TilesExport.xml"));
生成的XML如下所示。
<jaxb2Lists>
<tile>
<name>Test Name</name>
<id>1</id>
<imageName>TestImage.png</imageName>
<drawType>1</drawType>
<trueType>1</trueType>
<count>1</count>
<feature>1</feature>
</tile>
</jaxb2Lists>
JAXB_List類在下面的URL(我的另一個問題)中進行了詳細說明。 (顯然沒有人對此有答案。https://stackoverflow.com/questions/38472060/dynamic-xmlrootelement-name
因此,生成的XML具有除Sides成員變量之外的所有值。
我要去哪里錯了?
您需要一個公共getter作為您的sides
列表,並且該設置者需要命名為sides
。 就像是:
public List<Integer> getSides() {
return side;
}
public void setSides(List<Integer> sides) {
this.side = sides;
}
應該這樣做。 為了保持一致性,還可能需要將您的side
字段重命名為sides
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.