gpt4 book ai didi

java - 使用 JAXB 编码长原始类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:51:05 26 4
gpt4 key购买 nike

为了使用 JAXB 编码 long 原始类型,我使用了@XmlJavaTypeAdapter 注释,它将使非字符串类型适应字符串。即使它为 long 类型抛出错误。为什么会这样?如何对我的 long id 属性进行编码?

用户.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)

关于java - 使用 JAXB 编码长原始类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14053063/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com