0

I am using spring mvc with org.springframework.web.servlet.view.json.MappingJackson2JsonView to return json objects from controllers, To integrate with ember RestAdapter I need to return the json with namespace on it. How do I do that ? Currently I have the following controller which returns an Object (JSON) which can be a list of Customer Ids or List of Customer Objects,

@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public Object getCustomer(HttpServletRequest request, HttpServletResponse response) {
   if (request.getQueryString()!=null){
       List<Integer> customerIdList = new ArrayList<Integer>();
       customerIdList = customerDao.findAllCustomerIds();
       return customerIdList;
   } else {
       List<Customer> customerList = new ArrayList<Customer>();
       customerList = customerDao.findAllCustomers();
       return customerList ;
   }
}

The output I get is,

If I include a query string,

[ 1,2,3 ] 

else

[ {
    id: "1",
    name: "ABC Pty Ltd"
  },
  { 
    id: "2",
    name: "XYZ Ltd"
  },
  {
    id: "3",
    name: "Hello "
   }
 ]

The result I want is,

if I include query string,
 { customers : [ 1,2,3 ] };
else 
 { customers : [
                {
                   id: "1",
                   name: "ABC Pty Ltd"
                 },
                { 
                   id: "2",
                   name: "XYZ Ltd"
                 },
                {
                   id: "3",
                   name: "Hello "
                 }
               ]
 }

How can I achieve this ?

NUS
  • 383
  • 1
  • 6
  • 17

1 Answers1

0

Try putting your result in a map:

Map<String, List> result = new HashMap<>();      
if (request.getQueryString() != null) {
    List<Integer> customerIdList = customerDao.findAllCustomerIds();
    result.put("customers", customerIdList);
} else {
    List<Customer> customerList = customerDao.findAllCustomers();
    result.put("customers", customerList);
}
return result;

Also please note tht your GET can return two different things (a list of ids or a list of customares). This might indicate a smell in your API design.

  • This adds an extra step but works, I would like the serializer to do this, and also for single entity return also the namespace value is missing and I need to wrap the entity in a new entity so that namespace can be generated but i don't like this approach there should be a clean way of doing this, example I do like CustomerResponse c = new CustomerResponse(customer); and return the CustomerResponse – NUS Jan 14 '15 at 02:30
  • Think of JSON as an object notation. That is if your object is a collection of customers then you'll get `[ 1,2,3 ]` but if your object has a property customers being a collection of customers (you called it a _namespace_) then you'll have `{customers:[ 1,2,3 ]}` – Marek Lesiewski Jan 17 '15 at 17:44