gpt4 book ai didi

java - JAXB 编码/解码具有 List 变量成员的类对象

转载 作者:行者123 更新时间:2023-12-01 09:40:12 25 4
gpt4 key购买 nike

我正在尝试使用 JAXB 加载一系列 XML 文件,为每个类创建多个对象列表。

图 block 类

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>

下面的 URL 详细介绍了 JAXB_List 类,这是我的另一个问题。 (显然没有人能回答这个问题。 https://stackoverflow.com/questions/38472060/dynamic-xmlrootelement-name

因此生成的 XML 具有除 Sides 成员变量之外的所有值。

我哪里出错了?

最佳答案

您的 sides 列表需要一个公共(public) getter,并且 setter 需要命名为 sides。像这样的东西:

public List<Integer> getSides() {
return side;
}
public void setSides(List<Integer> sides) {
this.side = sides;
}

应该这样做。为了保持一致性,也可能值得将您的 side 字段重命名为 sides

关于java - JAXB 编码/解码具有 List 变量成员的类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38516780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com