2012-04-02 61 views
1

有沒有辦法將對象轉換爲GET請求的查詢參數? 某種將NameValuePair對象轉換爲name = aaa & value = bbb的序列化程序,以便字符串可以附加到GET請求。如何使用spring(或其他)將對象轉換爲查詢字符串?

換句話說,我正在尋找的是需要
1. URL(http://localhost/bla
2.對象庫:
public class Obj {
String id;
List<NameValuePair> entities;
}

並將其轉換爲:
http://localhost/bla?id=abc&entities[0].name=aaa&entities[0].value=bbb

春RestTemplate不是我正在尋找的,因爲它除了將對象轉換爲參數字符串之外,還處理所有其他事情。

+0

如果您正在使用RESTFUL通信是的。 – 2012-04-02 13:33:07

+0

任何示例/鏈接? – Dima 2012-04-02 13:34:09

+0

你可以在http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/ – 2012-04-02 13:35:08

回答

1

使用com.sun.jersey.api.client.Client:

Client.create().resource("url").queryParam(key, value).get() 
1
// object to Map 
ObjectMapper objectMapper = new ObjectMapper(); 
Map<String, String> map = objectMapper.convertValue(obj, new TypeReference<Map<String,String>>() {}); 

// Map to MultiValueMap 
LinkedMultiValueMap<String, String> linkedMultiValueMap = new LinkedMultiValueMap<>(); 
map.entrySet().forEach(e -> linkedMultiValueMap.add(e.getKey(), e.getValue())); 

// call RestTemplate.exchange 
return getRestTemplate().exchange(
     uriBuilder().path("your-path").queryParams(linkedMultiValueMap).build().toUri(), 
     HttpMethod.GET, 
     null, 
     new ParameterizedTypeReference<List<YourTypes>>() {}).getBody(); 
相關問題