如何使用spring(或其他任何东西)将对象转换为查询字符串?

Dim*_*ima 3 java http spring-mvc

有没有办法将对象转换为 GET 请求的查询参数?某种将 NameValuePair 对象转换为 name=aaa&value=bbb 的序列化程序,以便可以将该字符串附加到 GET 请求。

换句话说,我正在寻找一个需要
1. url ( http://localhost/bla)
2. Object: 并将其转换为:
public class Obj {
String id;
List<NameValuePair> entities;
}


http://localhost/bla?id=abc&entities[0].name=aaa&entities[0].value=bbb

Spring RestTemplate 不是我要找的,因为除了将对象转换为参数字符串之外,它还可以执行所有其他操作。

Bar*_*ler 7

// 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();
Run Code Online (Sandbox Code Playgroud)


she*_*hem 1

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

Client.create().resource("url").queryParam(key, value).get()
Run Code Online (Sandbox Code Playgroud)