Using JAXB with Character

こ雲淡風輕ζ 提交于 2021-02-07 22:55:52

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!