gpt4 book ai didi

json - Jaxb 是否需要 @XmlElement

转载 作者:数据小太阳 更新时间:2023-10-29 02:41:22 26 4
gpt4 key购买 nike

我的问题是,在进行 JSON 响应时,是否有必要在 pojo 中的每个元素之前添加 @XmlElement 以供 jaxb 获取。我正在使用 jersey-json 1.17 。我问这个的原因是因为,the example given on Jersey site不使用注解。

我得到一个作为 {} 的输出,但是当我在属性前添加 @XmlElement 时,我得到了预期的 JSON 输出。我是不是做错了什么,导致我的 JSON 字符串为空?

我的代码:

顶点列表在构造函数中填充。

这会产生 {} 的错误输出

@XmlRootElement
public class SquareModel {
List<Float> vertices = new ArrayList<Float>();
....
}

而这会生成正确的 JSON 字符串:

@XmlRootElement
public class SquareModel {
@XmlElement(name="vertices")
List<Float> vertices = new ArrayList<Float>();
....
}

返回 JSON 的我的资源类

@GET
@Produces(MediaType.APPLICATION_JSON)
public SquareModel getJsonString() {
return new SquareModel();
}

谢谢:)

最佳答案

不,默认情况下,JAXB (JSR-22@) 实现会将所有公共(public)字段和属性(get/set 组合)视为已映射(不需要 @XmlElement 注释)。

如果您想注释一个字段,我建议您使用 @XmlAccessorType(XmlAccessType.FIELD)

注释您的类

关于json - Jaxb 是否需要 @XmlElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15749599/

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