【发布时间】:2014-02-05 07:22:37
【问题描述】:
我正在使用 JAXB 编组和解组对象。我有一个Class MyBean,其中包含字符串列表作为字段并用@XmlAttribute 注释。
@XmlRootElement
public class MyBean {
public MyBean() {
super();
}
private List<String> actualValue;
@XmlAttribute
public List<String> getActualValue() {
if (actualValue == null) {
actualValue = new ArrayList<String>();
}
return actualValue;
}
public void setActualValue(List<String> values) {
this.actualValue = values;
}
}
以下是用于编组和取消编组 MyBean 的 Test 类。
public class Test {
public static void main(String[] args) {
try {
// create object ....
MyBean myBean = new MyBean();
List<String> values = new ArrayList<String>();
values.add("Sanjv Singh Baghel");
myBean.setActualValue(values);
// Marsheling
File file = new File("D://Temp//hello2.xml");
JAXBContext jaxbContext2 = JAXBContext.newInstance(MyBean.class);
Marshaller jaxbMarshaller2 = jaxbContext2.createMarshaller();
jaxbMarshaller2.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller2.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
jaxbMarshaller2.marshal(myBean, file);
// Un-Marsheling
JAXBContext jaxbContext = JAXBContext.newInstance(MyBean.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
// printing actual value
MyBean myBean2 = (MyBean) jaxbUnmarshaller.unmarshal(file);
List<String> actualValue = myBean2.getActualValue();
System.out.println(actualValue);
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
输出:
Before actualValue : ["sanjv singh baghel"]
After actualValue : ["sanjv, singh, baghel"]
奇怪的是,我在这里遇到的是原来的actualValue 只有一个带空格的字符串,在解组后,该单个字符串被转换为字符串列表(除以空格)。
我想知道为什么会这样/有什么问题。
为此,我找到了两种可能的解决方案:
- 将
@XmlAttribute替换为@XmlElement -
List<String> actualValue;& String 需要映射到 schema 简单类型
【问题讨论】:
标签: java jaxb marshalling unmarshalling