简体   繁体   中英

Jersey Jackson root name coming as ArrayList

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.

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);

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM