如何将JAXB解组为其枚举等效的整数?

时间:2015-08-11 01:11:14

标签: java xml enums jaxb unmarshalling

我有一个班级:

@Data
@XmlRootElement(name="root")
@XmlAccessorType(XmlAccessType.FIELD)
public class rootClass
{
    @XmlElement(name="test")
    public FeFiFo test;
}

enum FeFiFo
{
    FE,
    FI,
    FO,
}

和XML:

<root>
  <test>1</test>
</root>

如何将XML解组到类中,以便test属性变为FeFiFo.FI?目前它变为空。

1 个答案:

答案 0 :(得分:2)

您应该使用XmlJavaTypeAdapter

<强> rootClass

@Data
@XmlRootElement(name="root")
@XmlAccessorType(XmlAccessType.FIELD)
public class rootClass
{
    @XmlJavaTypeAdapter(EnumAdapter .class)
    @XmlElement(name="test")
    public FeFiFo test;
}

<强>适配器

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class EnumAdapter extends XmlAdapter<String, FeFiFo>
{

    public FeFiFo unmarshal(String value) {
        //if()
        //else if()
        //else

        return FeFiFo.FE;
    }

    public String marshal(FeFiFo value) {
        //if()
        //else if()
        //else
        return "0";
    }

}