I'm working on a project with JAXB but I run into a small problem with JAXB and the char datatype.
char gender = 'M';
Translates after marshalling into:
<gender>77</gender>
So I think that char is mapped to integer, but I simply want to map it to a String. How can I do this? Is it even possible?
JAXB simplifies access to an XML document from a Java program by presenting the XML document to the program in a Java format. The first step in this process is to bind the schema for the XML document into a set of Java classes that represents the schema.
To unmarshal an xml string into a JAXB object, you will need to create an Unmarshaller from the JAXBContext, then call the unmarshal() method with a source/reader and the expected root object.
JAXB is a java architecture for XML binding is an efficient technology to convert XML to and from Java Object. EclipseLink JAXB (MOXy) is one of JAXB implementation which is mostly used to create java classes from XML or JSON.
After some experimentation, there appears to be no way to configure JAXB to handle primitive chars properly. I'm having a hard time accepting it, though.
I've tried defining an XmlAdaptor
to try and coerce it into a String, but the runtime seems to only accept adapters annotated on Object types, not primitives.
The only workaround I can think of is to mark the char field with @XmlTransient
, and then write getters and setters which get and set the value as a String:
@XmlTransient
char gender = 'M';
@XmlElement(name="gender")
public void setGenderAsString(String gender) {
this.gender = gender.charAt(0);
}
public String getGenderAsString() {
return String.valueOf(gender);
}
Not very nice, I'll grant you, but short of actually changing your char field tobe a String, that's all I have.
@XmlJavaTypeAdapter(value=MyAdapter.class, type=int.class)
Thats the trick specify type to make it work with primitives
In your adapter
using the same in package-info will mean you do it globally for that package
Found this after experimenting.
public class MyAdapter extends XmlAdapter<String, Integer> {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With