我有一个 POJO,其中包含一个需要输出到 XML 且标记名称为“class”的字段。
使用 Jersey 2.0,如果客户端请求 JSON 响应,则 JSON 对象会正确输出属性名称“class”。
但是,如果客户端请求 XML 输出,Jersey 将失败并出现 HTTP 500 内部错误。
检查导致错误的语句是
@XmlElement(名称 = "类")
私有(private) int vclass;
删除 XmlElement 注释并允许 XML 使用 vclass 作为标记名称可以正常工作。
我如何指示 JAXB 使用 class 作为标记名称?
最佳答案
Why “class” cannot be use as tag name in JAXB
您可以在 JAXB 中使用“class”作为标记名称。
您可能遇到什么问题
默认情况下,JAXB 将公共(public)属性视为已映射。由于您注释了一个字段,因此您很可能会收到有关重复映射属性的异常。
Exception in thread "main" com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
Class has two properties of the same name "vclass"
this problem is related to the following location:
at public int forum27241550.Foo.getVclass()
at forum27241550.Foo
this problem is related to the following location:
at private int forum27241550.Foo.vclass
at forum27241550.Foo
为什么你做了什么解决了这个问题
您将以下内容发布为 answer :
Finally found out what's wrong.
Don't know why the annotation in variable declaration statement will cause problem.
Putting the @XmlElement annotation in the setter method work fine.
当您将注释移至属性时,该字段不再被视为已映射,因此不存在重复映射问题。
如何将注释保留在字段上
要注释字段,您应该在类上使用@XmlAccessorType(XmlAccessType.FIELD)
。
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Foo {
@XmlElement(name = "class")
private int vclass;
public int getVclass() {
return vclass;
}
public void setVclass(int vclass) {
this.vclass = vclass;
}
}
关于java - 为什么 "class"不能用作 JAXB 中的标记名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27241550/