Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: JAXB and using char

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?

like image 862
Korenaga Avatar asked Sep 23 '09 13:09

Korenaga


People also ask

How does JAXB work in Java?

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.

How do you Unmarshal XML string to Java object using JAXB?

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.

Can JAXB used for JSON?

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.


2 Answers

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.

like image 138
skaffman Avatar answered Oct 04 '22 22:10

skaffman


@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> {
like image 23
Abs Avatar answered Oct 04 '22 23:10

Abs