简体   繁体   中英

How do I get JAXB to choose enum?

I'm trying to convert the XML text to a Java object, but there is a number in the prQueryStatus XML attribute. The type of the Java field is an enum . Is there a way for JAXB to choose my enum ?

Strxml:

 <custom prQueryStatus="1" ></custom>

faulty row:

  CustAttrPrQuery custom = (CustAttrPrQuery)XmlOperations.deserializeFromXML(CustAttrPrQuery.class, strXmlCustom);

XmlOperations.deserializeFromXML():

public static Object deserializeFromXML(Class obj, String strXml) {

    Object result = null;
    JAXBContext jaxbContext;
    try {
        jaxbContext = JAXBContext.newInstance(obj);

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

        StringReader reader = new StringReader(strXml);

        result = unmarshaller.unmarshal(reader);
        return result;

    } catch (JAXBException e) {
       return new String("-3 JAXB deSerialize Error");
    }

}  

CustAttrPrQuery:

@XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.FIELD)
@XmlRootElement(name = CustAttrPrQuery.RootElement)
public class CustAttrPrQuery {

    public final static String RootElement = "custom";

    @javax.xml.bind.annotation.XmlAttribute
    private PrQueryStatus prQueryStatus = PrQueryStatus.NONE;

    public PrQueryStatus getPrQueryStatus() {
        return prQueryStatus;
    }

    public void setPrQueryStatus(PrQueryStatus prQueryStatus) {
        this.prQueryStatus = prQueryStatus;
    }

}

enum:

public enum PrQueryStatus {
  NONE,
  ACIK,
  TUMU
}

You need to annotate your enum type with @XmlEnum and its constants with @XmlEnumValue , so that JAXB will know how to map from XML attributes ( "0" , "1" , "2" ) to the enum constants ( NONE , ACIK , TUMU ):

@XmlEnum
public enum PrQueryStatus {
    @XmlEnumValue("0") NONE,
    @XmlEnumValue("1") ACIK,
    @XmlEnumValue("2") TUMU
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM