相关疑难解决方法(0)

使用JAXB编组长原始类型

为了使用JAXB编组一个长基本类型,我使用了XmlJavaTypeAdapter@annotation,它将非String类型调整为String.即使它为长类型抛出错误.为什么会这样?如何对我的longid属性进行编组?

User.java

class User {
    @XmlID
    @XmlJavaTypeAdapter(WSLongAdapter.class)
    private long id;
    // Other variables
    // Getter & Setter method
}    
Run Code Online (Sandbox Code Playgroud)

WSLongAdapter.java

    public class WSLongAdapter extends XmlAdapter<String, Long>{
        @Override
        public String marshal(Long id) throws Exception {
            if(id==null) return "" ;
            return id.toString();
        }
        @Override
        public Long  unmarshal(String id) throws Exception {
        return  Long.parseLong(id);
        }
     }
Run Code Online (Sandbox Code Playgroud)

MarshallTest.java

public static void main(String[] args) {
    try{
        JAXBContext jaxbContext= JAXBContext.newInstance(User.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        OutputStreamWriter writer = new OutputStreamWriter(System.out);
        // …
Run Code Online (Sandbox Code Playgroud)

java jaxb

6
推荐指数
2
解决办法
8602
查看次数

标签 统计

java ×1

jaxb ×1