gpt4 book ai didi

java - 为什么 "class"不能用作 JAXB 中的标记名称

转载 作者:行者123 更新时间:2023-11-30 08:18:46 24 4
gpt4 key购买 nike

我有一个 POJO,其中包含一个字段需要输出到带有标签名称“class”的 XML。

使用 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/

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