【问题标题】:Jackson JSON from a list, help formatting the JSONJackson JSON from a list,帮助格式化 JSON
【发布时间】:2012-06-16 19:55:43
【问题描述】:

我有以下课程....

@XmlType
@XmlRootElement(name = "milestones")
@XmlAccessorType(XmlAccessType.FIELD)
public static class Circle {
    public String type = "circle";
    public double cx;
    public double cy;
    public int r;
    public String title;
    public Integer width;   
}

我正在返回一个圈子列表(实际上是使用 JaxRS 和 RestEasy,它使用 Jackson)

我希望 Json 输出类似于

[{"type":"circle","cx":100.0,"cy":100.0,"r":0,"title":"test1","width":2},
{"type":"circle","cx":150.0,"cy":150.0,"r":0,"title":"test2","width":0}]

在我的开发机器上,输出是这样的,但在生产中它就像

[{"milestones":{"type":"circle","cx":100,"cy":100,"r":0,"title":"test1","width":2}}, 
{"milestones":{"type":"circle","cx":150,"cy":150,"r":0,"title":"test2","width":0}}]

有没有办法强制它使用第一种输出格式(没有列出名称)?

感谢您的帮助, 梅森

【问题讨论】:

    标签: json jax-rs jackson resteasy


    【解决方案1】:

    使用相同的代码库,两台机器上的输出不太可能不同。

    此行为是由 ObjectMapper 的 WRAP_ROOT_VALUE 功能驱动的,因此您可能想尝试使用下面的代码显式关闭它(您可能还想检查它是否在代码中的某个位置被显式打开,如默认禁用此功能)

    mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, false);
    

    由于您使用的是 RestEasy,因此您需要扩展 RestEasyJacksonProvider 以访问底层 ObjectMapper。

    【讨论】:

    • 非常感谢。我继续手动将 JSON 创建为字符串,但希望这对其他人或将来的我有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 2021-11-16
    • 1970-01-01
    相关资源
    最近更新 更多