简体   繁体   English

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

[英]How to JAXB Unmarshal an integer into its enum equivalent?

I have a class: 我有一堂课:

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

enum FeFiFo
{
    FE,
    FI,
    FO,
}

And an XML: 还有一个XML:

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

How can I unmarshal the XML into the class so that the test property becomes FeFiFo.FI? 如何将XML解组到类中,以便test属性成为FeFiFo.FI? Currently it becomes null. 当前,它变为空。

You should use an XmlJavaTypeAdapter 您应该使用XmlJavaTypeAdapter

rootClass rootClass

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

adapter 适配器

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";
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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