gpt4 book ai didi

java - 使用 JAXB 解码不起作用

转载 作者:行者123 更新时间:2023-11-29 05:15:42 25 4
gpt4 key购买 nike

我有一个简单的 XML,我想将其解码到模型类中。我已使用 JAXB 注释对类进行注释以定义访问类型 (FIELD):

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;

@XmlAccessorType(XmlAccessType.FIELD)
public class DtoTest {

private String name;

public DtoTest() {}

public DtoTest(String name) {
super();
this.name = name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "DtoTest [name=" + name + "]";
}
}

这是我的主类,我在其中对保存在字符串变量中的简单 XML 运行解码方法:

public class Test {

public static void main(String[] args) throws Exception {
Object obj = new DtoTest();
String testXML = "<dtoTest><name>example</name></dtoTest>";
obj = unmarshal(obj, testXML);
System.out.println(obj);
}

/* This is a generic unmarshall method which I've already used with success with other XML*/
public static <T> T unmarshal(T obj, String xml) throws Exception {
XMLInputFactory xif = XMLInputFactory.newFactory();
XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml));

Class<? extends Object> type = obj.getClass();
JAXBContext jc = JAXBContext.newInstance(type);
Unmarshaller unmarshaller = jc.createUnmarshaller();
obj = (T)unmarshaller.unmarshal(xsr, type).getValue();
xsr.close();

return obj;
}
}

每当我运行代码时,我都会得到相同的输出:

DtoTest [name=null]

我不明白我做错了什么。

最佳答案

我刚刚在 jdk1.7.0_67 上运行了您的代码,它可以正常工作。

DtoTest [name=example]

也许您对包含的库有一些问题?我只用普通的 java 运行它。

关于java - 使用 JAXB 解码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26635784/

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