2014-12-19 54 views
0

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

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

我婉结果t是,

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

我该如何做到这一点?

回答

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设计中有的气味

+0

这增加了一个额外的步骤,但工程,我想串行器做到这一点,也单个实体返回也缺少命名空间值,我需要包裹实体在一个新的实体,使命名空间可以生成,但我不喜欢这种方法,应该有一个干净的方式来做到这一点,例如我喜欢CustomerResponse c = new CustomerResponse(customer);并返回CustomerResponse – NUS 2015-01-14 02:30:53

+0

将JSON视为对象表示法。也就是说,如果你的对象是一群客户,那么你会得到'[1,2,3]',但是如果你的对象有一个客户属性集合的客户(你称之为_namespace_),那么你将拥有' {customers:[1,2,3]}' – 2015-01-17 17:44:30