问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/17972981/using-jaxb-with-character