Avinash
Avinash

Reputation: 603

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.

Upvotes: 1

Views: 1806

Answers (3)

Sunil Manheri
Sunil Manheri

Reputation: 2353

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

Upvotes: 0

Alexey Gavrilov
Alexey Gavrilov

Reputation: 10853

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.

Upvotes: 0

pgiecek
pgiecek

Reputation: 8230

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

Upvotes: 2

Related Questions