gpt4 book ai didi

java - JAXB 解码到列表

转载 作者:行者123 更新时间:2023-12-01 22:03:09 25 4
gpt4 key购买 nike

我正在尝试将此 XML 解码为 Java 对象,即包含电子邮件地址列表的 Customer 对象。

<customer>
<emailAddresses>janed@example.com</emailAddresses>
<emailAddresses>jdoe@example.org</emailAddresses>
</customer>

列表出现问题,我得到了正确的列表项数 (2),但 emailAddresses 标记的值为 null

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>janed@example.com</emailAddresses>"
+ " <emailAddresses>jdoe@example.org</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( "janed@example.com", msg.getEmailAddresses().get( 0 ).getEmailAddresses() );
}

最佳答案

emailAddresses EmailAddress领域默认情况下被视为子元素,期望 XML 为:

<customer>
<emailAddresses>
<emailAddresses>janed@example.com</emailAddresses>
</emailAddresses>
<emailAddresses>
<emailAddresses>jdoe@example.org</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;
}

关于java - JAXB 解码到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33350652/

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