title: spring generic json response
body: <p>I am using <code>Spring MVC</code> and returning <code>JSON</code> as response. I would like to create a generic <code>JSON</code> response where I can put in any TYPE and want the response to look like this</p>
  
  <pre><code>{
      status : "success",
      data : {
          "accounts" : [
              { "id" : 1, "title" : "saving", "sortcode" : "121212" },
              { "id" : 2, "title" : "current", "sortcode" : "445566" },
          ]
       }
  }
  </code></pre>
  
  <p>So I created a <code>Response&lt;T&gt;</code> object</p>
  
  <pre><code>public class Response&lt;T&gt; {
  
      private String status;
      private String message;
      T data;
  ...
  ...
  }
  </code></pre>
  
  <ol>
  <li>Is this the correct way of doing this, or is there a better way?.</li>
  <li>How do you use this Response object in <code>Spring</code> controller to return an empty response object and/or a populated response object.</li>
  </ol>
  
  <p>Thanks in advance GM</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>In order to get the similar <code>JSON</code> output as the one described, i.e. with "accounts" key in <code>JSON</code>, I had to use <code>Response&lt;Map&lt;String, List&lt;Account&gt;&gt;&gt;</code> the following in the controller:</p>
  
  <pre><code>@RequestMapping(value = {"/accounts"}, method = RequestMethod.POST, produces = "application/json", headers = "Accept=application/json")
      @ResponseBody
      public Response&lt;Map&lt;String, List&lt;Account&gt;&gt;&gt; findAccounts(@RequestBody AccountsSearchRequest request) {
          //
          // empty accounts list
          //
          List&lt;Account&gt; accountsList = new ArrayList&lt;Account&gt;();
  
          //
          // response will hold a MAP with key="accounts" value="List&lt;Account&gt;
          //
          Response&lt;Map&lt;String, List&lt;Account&gt;&gt;&gt; response = ResponseUtil.createResponseWithData("accounts", accountsList);
  
          try {
              accountsList = searchService.findAccounts(request);
  
              response = ResponseUtil.createResponseWithData("accounts", accountsList);
              response.setStatus("success");
              response.setMessage("Number of accounts ("+accounts.size()+")");
          } catch (Exception e) {
              response.setStatus("error");
              response.setMessage("System error " + e.getMessage());
              response.setData(null);
          }
  
          return response;
      }
  </code></pre>
  
  <p>Is this the right way of doing this? i.e. in order to get the "accounts" key in <code>JSON</code> output?</p>