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 service. Since it is a free form entry, if i give a wrong fruit say "Guva" then instead of throwing an exception it is returning it as null after doing the UnMarshalling.
How can i avoid this? Should i use custom enum class instead of JAXB generated one. Please give some example. i.e.
regards sri
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
By default your JAXB (JSR-222) implementation will not fail on any conversion exceptions. If you are using the JAXB APIs to do the unmarshalling then you can set a
ValidationEventHandler
to catch any problems. Below is an example.Root
Fruit
Demo
JAXB REFERENCE IMPLEMENTATION
Unfortunately there appears to be a bug in the JAXB RI as a validation event is not being through for the invalid enum value.
Work Around
Write your own
XmlAdapter
to handle to conversion to/from theFruit
enum:FruitAdapter
Fruit
Use the
@XmlJavaTypeAdapter
annotation to associate theXmlAdapter
with theFruit
enumb.New Output
EclipseLink JAXB (MOXy)
Using MOXy both validation events are thrown. To specify MOXy as your JAXB provider see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html.
Short answer based on original reply. You need to do 2 things
Fruit.java defines and uses the adapter
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)
An alternative consists in generating XSD schemas as presented in here: how can i unmarshall in jaxb and enjoy the schema validation without using an explicit schema file.
Here is the snippet I stole from dolbysurnd: