我正在使用spring mvc和org.springframework.web.servlet.view.json.MappingJackson2JsonView从控制器返回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 "
}
]
}
我怎样才能做到这一点?
尝试将结果放入地图中:
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列表或自定义列表(。这可能表示 API 设计中有异味。