我想解析這個XML到Java對象,一個包含EmailAdresses列表的Customer對象。JAXB Unmarshall到列表
<customer>
<emailAddresses>[email protected]</emailAddresses>
<emailAddresses>[email protected]</emailAddresses>
</customer>
經與列表中的一個問題,我得到的列表項(2),但爲EmailAddresses變量的值正確的號碼是空
Customer.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());
}
我試着按照下面添加幾個註釋,但沒有運氣。 – MikeJ