Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert object to query string with spring (or anything else)?

Is there a way to convert object to query parameters of GET request? Some kind of serializer that converts NameValuePair object to name=aaa&value=bbb, so that string can be attached to the GET request.

In other words, I'm looking for a library that takes
1. url (http://localhost/bla)
2. Object:
public class Obj {
String id;
List<NameValuePair> entities;
}

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

Spring RestTemplate is not what I'm looking for as it does all other things except converting object to parameters string.

like image 476
Dima Avatar asked Feb 20 '23 23:02

Dima


1 Answers

// 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();
like image 80
BartoszMiller Avatar answered Apr 07 '23 23:04

BartoszMiller