使用JAXB对长基本类型进行编组 [英] Marshaling a long primitive type using JAXB

查看:76
本文介绍了使用JAXB对长基本类型进行编组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了使用JAXB编组一个长基本类型,我使用了@ XmlJavaTypeAdapter 注释,它将非String类型调整为String。即使它为长类型抛出错误。为什么会这样?如何在 long id属性上进行编组?

To marshal a long primitive type using JAXB, I have used @XmlJavaTypeAdapter annotation, which will adapt non-String type to a String. Even though it throw error for long type. Why is it so? How can I do marshalling on my long id attribute?

User.java

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

WSLongAdapter.java

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);
        }
     }

MarshallTest.java

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);
        // Manually open the root element
        writer.write("<user>");
        // Marshal the objects out individually
        marshaller.marshal(new User(), writer);
        // Manually close the root element
        writer.write("</user>");
        writer.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

错误:

  com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 4 counts of IllegalAnnotationExceptions
Adapter com.v4common.shared.util.other.WSLongAdapter is not applicable to the field type long. 
    this problem is related to the following location:
        at @javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter(type=class javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter$DEFAULT, value=class com.v4common.shared.util.other.WSLongAdapter)
        at private long com.v4common.shared.beans.usermanagement.User.id
        at com.v4common.shared.beans.usermanagement.User
Property "id" has an XmlID annotation but its type is not String.
    this problem is related to the following location:
        at private long com.v4common.shared.beans.usermanagement.User.id
        at com.v4common.shared.beans.usermanagement.User
There are two properties named "id" 


推荐答案

以下可能有效:

class User {
    @XmlID
    @XmlJavaTypeAdapter(WSLongAdapter.class)
    @XmlElement(type=Long.class)
    private long id;
    // Other variables
    // Getter & Setter method
}    

这篇关于使用JAXB对长基本类型进行编组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆