[英]Marshaling a long primitive type using 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<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
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"
在注釋中指定基元類:
@XmlJavaTypeAdapter(type=long.class, value=WSLongAdapter.class)
以下可能有效:
class User {
@XmlID
@XmlJavaTypeAdapter(WSLongAdapter.class)
@XmlElement(type=Long.class)
private long id;
// Other variables
// Getter & Setter method
}
創建使用返回String
@XmlID
注釋的新getter
@XmlAccessorType(XmlAccessType.FIELD)
class User {
private long id;
@XmlID
public String getReferenceId() {
return Long.toString(id);
}
}
此解決方案的唯一缺點是序列化XML中存在附加標記(在本例中為<referenceId>
)。 我嘗試通過使用@XmlTransient
注釋getter來刪除它,但后來我收到錯誤通知引用類中不存在ID。
只需更換
@XmlElement(type=Long.class)
private long id;
同
@XmlSchemaType(name = "long")
protected Long id;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.