Jersey Jackson root name coming as ArrayList

独自空忆成欢 提交于 2019-12-25 03:55:32

问题


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}]
}

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}]
}

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


回答1:


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.

The mapper provides access to ObjectWriter builder,

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

And the writer has withRootName() method that is what you need.

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

See code snippet below.

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



回答2:


By default Jackson may not recognize the JAXB annotations but you can customise the object mapper to do this.

If you want to stick to the Jackson annotations, you can use @JsonRootName to indicate name to use for root-level wrapping.




回答3:


Another option is to override method findRootName() in JaxbAnnotationIntrospector and use this inside ObjectMapper.

So the code will look like:

@Override
public String findRootName(AnnotatedClass ac) {
    // will return "employees" for @XmlType(name = "employees")
    // Or you can return the class name itself
    return ac.getAnnotations().get(XmlType.class).name();
}

Reference: Customizing root name in Jackson JSON provider



来源:https://stackoverflow.com/questions/24710830/jersey-jackson-root-name-coming-as-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!