Search code examples
javajsonjax-rsjavax.ws.rs

JAX-RS How to return a list as Json with field name


I have a list which I want to return as a Response. But I want to prepend it with a field name.

List<String> res = ...
return Response.ok(res, MediaType.APPLICATION_JSON_TYPE).build();

This returns only the list

["abcd","efgh"]

But I want to return like

{
  "field" : ["abcd","efgh"]
}

Thanks..


Solution

  • Use a map.

    List<String> list = ...
    Map<String, List<String>> res = new HashMap<>();
    res.put("field", list);
    return Response.ok(res, MediaType.APPLICATION_JSON_TYPE).build();