带有ember命名空间的JSON视图

时间:2014-12-19 03:53:34

标签: json spring jackson fasterxml

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

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

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分: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列表或惯例列表)。这可能表示API设计中存在气味