Handling invalid enum values while doing JAXB Unmarshalling

后端 未结 3 1613
野趣味
野趣味 2021-01-02 05:14

My Jaxb has created a Enum class based on the XML schema set up.

**enum Fruit {
    APPLE,ORANGE;
}**

I am using a SOAP UI to check my web

3条回答
  •  情话喂你
    2021-01-02 05:49

    Short answer based on original reply. You need to do 2 things

    1. implement custom adapter to raise and exception
    2. add event handler to fail unmarshalling

    Fruit.java defines and uses the adapter

    package forum12147306;
    
    import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
    
    @XmlJavaTypeAdapter(FruitAdapter.class)
    public enum Fruit {
    
        APPLE, 
        ORANGE;
    
    }
    
    class FruitAdapter extends XmlAdapter {
    
        @Override
        public String marshal(Fruit fruit) throws Exception {
            return fruit.name();
        }
    
        @Override
        public Fruit unmarshal(String string) throws Exception {
            try {
                return Fruit.valueOf(string);
            } catch(Exception e) {
                throw new JAXBException(e);
            }
        }
    }
    

    The event handler for unmarshaller that fails parsing on error - i.e it returns false (you might need to decide when to fail and when not to fail)

        JAXBContext jc = JAXBContext.newInstance(Root.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setEventHandler(new ValidationEventHandler() {
            @Override
            public boolean handleEvent(ValidationEvent validationEvent) {
                 return false;
            }
        });
    

提交回复
热议问题