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?
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 enableSerializationFeature.WRAP_ROOT_VALUE
like you mentioned above and add the annotation to the class:This will wrap the objects themselves, not the list:
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:
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.