简体   繁体   中英

JAXB - generating classes from XSD - converting enums to strings

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 ?

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.

jaxb:globalBindings typesafeEnumBase =“xs:boolean”将起作用 - 将其留空,因为建议对绑定模式无效。

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

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