2014-12-19 18 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