泽西杰克逊的根名称来自ArrayList [英] Jersey Jackson root name coming as ArrayList

查看:130
本文介绍了泽西杰克逊的根名称来自ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象的数组列表。数组列表。 Employee类使用@XMLRootElement(name =employees)进行注释。我使用jersey 1.9.1,Jackson 1.9.2和POJOMappingFeature。响应类似于

I have an array list of objects. ArrayList. The Employee class is annotated with @XMLRootElement(name = "employees"). I use jersey 1.8.1, Jackson 1.9.2 with POJOMappingFeature.The response is like

{
    ArrayList: [{name: John, age: 28}, {name: Mike, age:29}]
}

如何让jackson在json响应中显示正确的根名称(employees)。我也尝试在Employee类上使用@JsonName(value =employees)。我需要在不使用带有属性List的EmployeeListWrapper之类的列表包装器的情况下执行此操作。我希望得到的反应如

How do i make jackson display the correct root name (employees) in the json response. i tried using @JsonName(value = "employees") on Employee class also. I need to do this without using a list wrapper like EmployeeListWrapper with attribute List. i would like to have the response like

{
    employees: [{name: John, age: 28}, {name: Mike, age:29}]
}

是否可以这样做使用任何jackson对象映射器配置。任何帮助都将受到高度赞赏。

Is it possible to do this using any jackson object mapper configuration. Any help would be highly appreciated.

推荐答案

您可能无法通过 @XMLRootElement @JsonRootName 注释,因为注释必须放在 ArrayList 类本身。因为你需要在没有任何收集包装的情况下进行,所以你必须直接使用Jackson ObjectMapper

You probably will not achieve this with @XMLRootElement or @JsonRootName annotations since the annotation would have to be put on the ArrayList class itself. And since you require to do it without any collection wrapper, then you will have to use Jackson ObjectMapper directly.

映射器提供对 ObjectWriter 构建器的访问,

The mapper provides access to ObjectWriter builder,


可用于的构建器对象序列化参数的每序列化配置,例如要使用的JSON视图和根类型。

Builder object that can be used for per-serialization configuration of serialization parameters, such as JSON View and root type to use.

作者有 withRootName()您需要的方法。


使用指定的配置构造新实例的方法用于根元素包装的根名称。

Method for constructing a new instance with configuration that specifies what root name to use for "root element wrapping".

请参阅下面的代码段。

ObjectWriter writer = ObjectMapper.writer().withRootName("employees");
writer.writeValueAsString(employees);

这篇关于泽西杰克逊的根名称来自ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆