Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson - Wrapping a list of objects with root object

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?

like image 906
user1782427 Avatar asked Jan 31 '13 17:01

user1782427


1 Answers

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.

like image 121
Sam Berry Avatar answered Sep 19 '22 23:09

Sam Berry