简体   繁体   中英

Java JAXB unmarshaling Enum

My Enum type ProductType is properly saving to XML but it doesn't want to unmarshal when opening the file.

I made EnumAdapter:

public class EnumAdapter extends XmlAdapter<String, ProductType>
{
    @Override
    public ProductType unmarshal(String value) throws Exception {
        try {
            return ProductType.valueOf(value);
        }
        catch(Exception e) {
            throw new JAXBException(e);
        }
    }

    @Override
    public String marshal(ProductType value) {
        return value.toString();
    }

}

My Product class:

public class Product {

    private final IntegerProperty ilosc; //quantity
    private final StringProperty nazwa;  //name
    private final ObjectProperty<ProductType> typ; //type
    private final BooleanProperty dostepnosc;

    public Product()
    {
        this(null, 0, ProductType.ALKOHOL, true);
    }


    public Product(String nazwa, int ilosc, ProductType typ, boolean dostepnosc) {
        this.nazwa = new SimpleStringProperty(nazwa);
        this.ilosc = new SimpleIntegerProperty(ilosc);
        this.typ = new SimpleObjectProperty<>(typ);
        this.dostepnosc = new SimpleBooleanProperty(dostepnosc);
    }
.
.
.
@XmlJavaTypeAdapter(EnumAdapter.class)
    public ProductType getTyp() {
        return typ.get();
    }

After opening the XML in my app enum is always setting to the value from default constructor (which is ALCOHOL, if I change it, enum is setting to whatever it is). I also know that marshalling from EnumAdapter works properly, I can change it to whatever I want. Please help.

I solved it, I was missing proper setting function:

public void setTyp(ProductType type){
        this.typ.setValue(type);

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