JAXB and property ordering

2019-01-10 18:27发布

I want the serialized XML output from my Java class to honor the ordering of the properties in the Java class.

It seems that JAXB orders alphabetically.

I can override this by using @XmlType with propOrder and specifying ALL of the properties, but I have a class with many properties and these are not yet finalized.

I read that specifying an empty propOrder would do it but it don't.

My example class:

package test;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement
//@XmlType(propOrder={"company", "scheme", "agreementNumber"})
@XmlType(propOrder={}) // makes no difference - still alphabetical in XML 
public class CustomerPlan2 {

    private String company;
    private String scheme;
    private String agreementNumber;

    @XmlElement(name="Company")
    public String getCompany() {
        return company;
    }
    public void setCompany(String company) {
        this.company = company;
    }

    @XmlElement(name="Scheme")
    public String getScheme() {
        return scheme;
    }
    public void setScheme(String scheme) {
        this.scheme = scheme;
    }

    @XmlElement(name="AgreementNumber")
    public String getAgreementNumber() {
        return agreementNumber;
    }
    public void setAgreementNumber(String agreementNumber) {
        this.agreementNumber = agreementNumber;
    }
}

My serialize code:

    CustomerPlan2 cp2 = new CustomerPlan2();

    cp2.setCompany("company");
    cp2.setScheme("scheme");
    cp2.setAgreementNumber("agreementnumber");
    JAXBContext context = JAXBContext.newInstance(CustomerPlan2.class);
    Marshaller marshaller = context.createMarshaller();

    marshaller.marshal(cp2, new FileWriter("C:\\temp\\out.xml"));

Output:

    <customerPlan2>
      <AgreementNumber>agreementnumber</AgreementNumber> 
      <Company>company</Company> 
      <Scheme>scheme</Scheme> 
    </customerPlan2>

I want my output to be (as the property order of my class):

    <customerPlan2>
      <Company>company</Company>
      <Scheme>scheme</Scheme> 
      <AgreementNumber>agreementnumber</AgreementNumber> 
    </customerPlan2>

Thanks for any help on this.

8条回答
疯言疯语
2楼-- · 2019-01-10 19:04

According to this, the order of sibling XML elements is not guaranteed.

查看更多
不美不萌又怎样
3楼-- · 2019-01-10 19:04

You have to add the propOrder and the XmlAccessType annotations to the class.

@XmlAccessorType(XmlAccessType.FIELD)

@XmlType(propOrder = {"PartyType","PartyName","PartyAddress"})
查看更多
登录 后发表回答