我正在尝试将XML编组为Java对象,这是一个包含EmailAdresses列表的Customer对象。
<customer>
<emailAddresses>[email protected]</emailAddresses>
<emailAddresses>[email protected]</emailAddresses>
</customer>
列表出现问题,我得到了正确数量的列表项(2),但是emailAddresses标记的值为null
客户.java
@XmlRootElement( name = "customer" )
public class Customer
{
private List<EmailAddress> emailAddresses;
public Customer()
{
emailAddresses = new ArrayList<EmailAddress>();
}
public List<EmailAddress> getEmailAddresses()
{
return emailAddresses;
}
public void setEmailAddresses( List<EmailAddress> emailAddresses )
{
this.emailAddresses = emailAddresses;
}
}
EmailAddress.java
public class EmailAddress
{
private String emailAddresses;
public String getEmailAddresses()
{
return emailAddresses;
}
public void setEmailAddresses( String emailAddresses )
{
this.emailAddresses = emailAddresses;
}
}
失败单元测试
@Test
public void shouldDeserialiseCusomerXMLToObject() throws JAXBException
{
String xml = "<customer>"
+ " <emailAddresses>[email protected]</emailAddresses>"
+ " <emailAddresses>[email protected]</emailAddresses>"
+ "</customer>";
JAXBContext jaxbContext = JAXBContext.newInstance( Customer.class );
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader( xml );
Customer msg = ( Customer ) jaxbUnmarshaller.unmarshal( reader );
// This passes, I have 2 emailAddresses
assertEquals( 2, msg.getEmailAddresses().size() );
// This fails, I have a null pointer instead of the email address
assertEquals( "[email protected]", msg.getEmailAddresses().get( 0 ).getEmailAddresses() );
}
最佳答案
默认情况下,emailAddresses
的EmailAddress
字段被视为子元素,期望XML为:
<customer>
<emailAddresses>
<emailAddresses>[email protected]</emailAddresses>
</emailAddresses>
<emailAddresses>
<emailAddresses>[email protected]</emailAddresses>
</emailAddresses>
</customer>
由于外部
<emailAddresses>
元素不包含内部<emailAddresses>
元素,因此永远不会分配该字段。您希望
emailAddresses
的EmailAddress
字段是(外部)<emailAddresses>
元素的值,因此必须通过指定JAXB
批注告诉@XmlValue
:@XmlValue
public String getEmailAddresses()
{
return emailAddresses;
}
@XmlValue
批注与@XmlAttribute
结合使用时特别有用,以支持如下XML:<Person sex="male" age="25">John Doe</Person>
上课的地方是:
public class Person {
public enum Sex {
@XmlEnumValue("male") MALE,
@XmlEnumValue("female") FEMALE,
}
@XmlAttribute
private Sex sex;
@XmlAttribute
private int age;
@Value
private String name;
}