使用JAXB对长基本类型进行编组

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

User.java

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

WSLongAdapter.java

  public class WSLongAdapter extends XmlAdapter{ @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

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

在注释中指定基元类:

 @XmlJavaTypeAdapter(type=long.class, value=WSLongAdapter.class) 

创建使用返回String @XmlID注释的新getter

 @XmlAccessorType(XmlAccessType.FIELD) class User { private long id; @XmlID public String getReferenceId() { return Long.toString(id); } } 

此解决方案的唯一缺点是序列化XML中存在附加标记(在本例中为 )。 我试图通过使用@XmlTransient注释getter来删除它,但后来我收到错误通知引用类中不存在ID。

只需更换

  @XmlElement(type=Long.class) private long id; 

  @XmlSchemaType(name = "long") protected Long id;