Jackson - Wrapping a list of objects with root object

10.2k Views Asked by At

My Controller returns a list of MyObj objects (using @ResponseBody)

public MyObj 
{
   int a;
   int b;
}

The return JSON looks like this:

[{"a":1,"b":2},{"a":2,"b":2}]

I would like to wrap this JSON so it will return something like:

{ "data": [{"a":1,"b":2},{"a":2,"b":2}]}

From what i read i need to enable SerializationConfig.Feature.WRAP_ROOT_VALUE or (?) use @JsonRootName("data") on top of my controller.

Also tried the @XmlRootElement, nothing seems to work. Any idea what is the right way to wrap the list of objects with a root name?

2

There are 2 best solutions below

2
On

It sounds like you're talking about putting @JsonRootName on the list rather than the object, which won't accomplish what you're trying to do.

If you would like to use @JsonRootName you'll want to enable SerializationFeature.WRAP_ROOT_VALUE like you mentioned above and add the annotation to the class:

@JsonRootName("data")
public MyObj {
    int a;
    int b;
}

This will wrap the objects themselves, not the list:

{
    "listName": [
        {
            "data": {"a":1, "b":2}
        },
        {
            "data": {"a":2, "b":2}
        }
    ]
}

If you want to wrap the list in an object, perhaps creating a generic object wrapper is the best solution. This can be accomplished with a class like this:

public final class JsonObjectWrapper {
    private JsonObjectWrapper() {}

    public static <E> Map<String, E> withLabel(String label, E wrappedObject) {
        return Collections.singletonMap(label, wrappedObject);
    }
}

Then before you send your list back with the response, just wrap it in JsonObjectWrapper.withLabel("data", list) and Jackson takes care of the rest.

0
On

This should do the job:

    List<MyObj> myList;
    
    ObjectWriter ow = mapper.writer()
            .with(SerializationFeature.WRAP_ROOT_VALUE)
            .withRootName("data");
    
    System.out.println(ow.writeValueAsString(myList));