0

我正在使用带有 org.springframework.web.servlet.view.json.MappingJackson2JsonView 的 spring mvc 从控制器返回 json 对象,要与 ember RestAdapter 集成,我需要返回带有命名空间的 json。我怎么做 ?目前我有以下控制器,它返回一个对象(JSON),它可以是客户 ID 列表或客户对象列表,

@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 ;
   }
}

我得到的输出是,

如果我包含一个查询字符串,

[ 1,2,3 ] 

别的

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

我想要的结果是,

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 "
                 }
               ]
 }

我怎样才能做到这一点?

4

1 回答 1

0

尝试将您的结果放在地图中:

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;

另请注意,您的 GET 可以返回两种不同的东西(id 列表或 customares 列表)。这可能表明您的 API 设计中有异味

于 2014-12-20T11:34:39.067 回答