Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB - generating classes from XSD - converting enums to strings

Tags:

java

jaxb

Using JAXB, we generate our Java beans directly. In the XSD, we have an enumerated type:

  <xs:simpleType name="promptBeforeCloseType">
    <xs:restriction base="xs:string">
     <xs:enumeration value="default"/>
     <xs:enumeration value="always"/>
     <xs:enumeration value="never"/>
    </xs:restriction>
  </xs:simpleType>

JAXB generates an enumerated type for the field using this type. We would like to have it converted to a String in the generated Java class, because those classes are mapped to ActionScript classes, and there is no enumerated type in ActionScript.

Is there a way to do it, implementing some kind of converter ? May be with XmlJavaTypeAdapter ?

like image 657
nicoulaj Avatar asked Jan 24 '23 01:01

nicoulaj


2 Answers

You can force XJC to not generate enums. See the "Global Binding Declarations" section of this document:

If typesafeEnumBase is set to xsd:string, it would be a global way to specify that all simple type definitions deriving directly or indirectly from xsd:string and having enumeration facets should be bound by default to a typesafe enum. If typesafeEnumBase is set to an empty string, "", no simple type definitions would ever be bound to a typesafe enum class by default.

like image 107
skaffman Avatar answered Jan 25 '23 14:01

skaffman


Check out the [Overriding the Datatype][1] section of the JAXB tutorial. You can do this with a customised bindings file set up similar to the example at the bottom of the page.

I think you'd have to write your own conversion method (and thus class) unfortunately since there doesn't seem to be one built-in (likely due to the fact that the JAXB-generated enums have no common superclass). But all you'd need to do is call the value() method on your enum object, which will return the String that mapped to it.

[1]: https://jaxb.dev.java.net/tutorial/section_5_6_1-Overriding-the-Datatype.html#Overriding the Datatype

like image 22
Andrzej Doyle Avatar answered Jan 25 '23 15:01

Andrzej Doyle