使用 JAXB 将 Java 对象转换为 XML - 注释问题

Java object into XML conversion using JAXB - annotation issue

public class RequestXml // this pojo for RequestXML
{
    private Contact[] Contact;

    public Contact[] getContact ()
    {
        return Contact;
    }

    @XmlElement(name="Contact")
    public void setContact (Contact[] Contact)
    {
        this.Contact = Contact;
    }
}

另一个pojo

public class Contact  // this class is for contact
{
    private String content;
    private String role;

    public String getContent ()
    {
        return content;
    }

    @XmlElement(name="content")
    public void setContent (String content)
    {
        this.content = content;
    }   

    public String getRole ()
    {
        return role;
    }

    @XmlElement(name="role")
    public void setRole (String role)
    {
        this.role = role;
    }
}

因为我在编组时得到如下结果

<Contact role="firstUser"/>
<Contact role="secondUser"/>
<Contact role="LastUser"/>

预期输出如下:

<Contact role="firstUser">aaaa</Contact>
<Contact role="secondUser">bbbb</Contact>
<Contact role="LastUser">cccc</Contact>

请帮我解决这个问题。

要将字段编组为内容,请使用 @XmlValue 注释。要将其编组为属性,请使用 @XmlAttribute。这是 Contract POJO 以及我的测试的样子:

@XmlRootElement
public class RequestXml {
    private Contact[] contact;

    @XmlElement(name = "Contact")
    public Contact[] getContact() {
        return contact;
    }

    public void setContact(Contact[] Contact) {
        this.contact = Contact;
    }
}

public class Contact {
    private String content;
    private String role;

    public Contact(String content, String role) {
        this.content = content;
        this.role = role;
    }

    @XmlValue
    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @XmlAttribute
    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }
}

测试:

public class JaxbTest {

    @Test
    public void testObjectToXml() throws JAXBException {
        RequestXml requestXml = new RequestXml();
        requestXml.setContact(new Contact[]{new Contact("aaa", "bbb")});
        JAXBContext jaxbContext = JAXBContext.newInstance(RequestXml.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(requestXml, System.out);
    }
}

这提供了以下输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<requestXml>
    <Contact role="bbb">aaa</Contact>
</requestXml>

编辑:另外,请参阅 以了解注释 getters/setters 和字段的区别。