我正在使用jaxb将xml响应转换为java对象,我已经尝试过,但是对于嵌套的类对象,我得到了null。
XML字符串
<person>
<name>name</name>
<age>12</age>
<address>
<info>
<contactadress>
<city>
</city>
<phone>
</phone>
</contactadress>
</info>
</address>
</person>
映射java类
@XmlRootElement(name = "person")
public class person
{
@XmlElement(name = "name")
String name;
@XmlElement(name = "age")
int age:
@XmlElement(name = "address/info/contactadress")
person.Address address;
@XmlRootElement(name = "contactadress")
public static class Address{
@XmlElement(name = "city")
String city;
@XmlElement(name = " phone")
String phone;
}
}
JaxB代码:
public Person parseXml(String xmlResponse, Person pserson)
{
StringReader stringReader = new StringReader(xmlResponse);
JAXBContext jaxbContext = JAXBContext.newInstance(pserson.class);
XMLInputFactory xif = XMLInputFactory.newInstance();
XMLStreamReader xsr = xif.createXMLStreamReader(stringReader);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
return unmarshaller.unmarshal(xsr);
}
转换后,获取地址对象为空。
答案 0 :(得分:0)
你的Person类看起来应该是这样的
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"name",
"age",
"address"
})
@XmlRootElement(name = "person")
public class Person {
@XmlElement(required = true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "NCName")
protected String name;
@XmlElement(required = true)
protected BigInteger age;
@XmlElement(required = true)
protected Address address;
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the age property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getAge() {
return age;
}
/**
* Sets the value of the age property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setAge(BigInteger value) {
this.age = value;
}
/**
* Gets the value of the address property.
*
* @return
* possible object is
* {@link Address }
*
*/
public Address getAddress() {
return address;
}
/**
* Sets the value of the address property.
*
* @param value
* allowed object is
* {@link Address }
*
*/
public void setAddress(Address value) {
this.address = value;
}
}
答案 1 :(得分:0)
@XmlElement
注释不允许您像在问题中一样指定路径作为元素名称。相反,您需要每个嵌套级别的类。如果您愿意,可以通过XmlAdapter
来使用这些课程(请参阅:Access attribute of internal element in the most simple way)。
@XmlElement(name = "address/info/contactadress")
person.Address address;
在EclipseLink JAXB (MOXy)中,我们提供@XmlPath
扩展程序,您可以执行此操作:
@XmlPath("address/info/contactadress")
person.Address address;
我在博客上写了更多关于此用例的内容: