Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JAXB with Character

Tags:

java

jaxb

I have an @XMLElement that is of type Character but when it get marshalled it appears to get put into a binary string so for example...

'n' becomes 110
'e' becomes 101

Short of converting them to Strings is there a way I can output the text char instead of the representation?

like image 901
Jackie Avatar asked Sep 07 '25 12:09

Jackie


1 Answers

You could write an XmlAdapter. An XmlAdapter allows you to convert one type of object to another for the purposes of marshalling/unmarshalling.

XmlAdapter (CharacterAdapter)

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class CharacterAdapter extends XmlAdapter<String, Character> {

    @Override
    public Character unmarshal(String v) throws Exception {
        return v.charAt(0);
    }

    @Override
    public String marshal(Character v) throws Exception {
        return new String(new char[] {v});
    }

}

Java Model

The XmlAdapter is specified using the @XmlJavaTypeAdapter annotation:

import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement
public class Foo {

    private Character bar;

    @XmlJavaTypeAdapter(CharacterAdapter.class)
    public Character getBar() {
        return bar;
    }

    public void setBar(Character bar) {
        this.bar = bar;
    }

}

For More Information

  • http://blog.bdoughan.com/2010/07/xmladapter-jaxbs-secret-weapon.html
  • http://blog.bdoughan.com/2012/02/jaxb-and-package-level-xmladapters.html
like image 72
bdoughan Avatar answered Sep 10 '25 04:09

bdoughan