BartoszMiller
BartoszMiller

Reputation: 1227

Convert Java object fields to query parameters in URI

My problem is: how can I add all fields from my Java object to URI as query params.

I'm trying to call HTTP GET request with multiple query parameters. All these query parameters come from one Java object. I'm using RestTemplate provided by Spring Framework and ObjectMapper provided by Jackson.

    @Override
public List<MyTypes> find(MyFilter myFilter) {

    // object to Map
    ObjectMapper objectMapper = new ObjectMapper();
    Map<String, String> map = objectMapper.convertValue(myFilter, 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(RestResourcePaths.My_PATH).queryParams(linkedMultiValueMap).build().toUri(),
            HttpMethod.GET,
            null,
            new ParameterizedTypeReference<List<MyTypes>>() {}).getBody();

The following works as expected, however I wonder if there is a simpler way to achieve it.

Upvotes: 5

Views: 7243

Answers (2)

Tim Gee
Tim Gee

Reputation: 1062

I wrote a jackson module to do this - convert a typed object directly into an HTTP query string.

https://github.com/trickl/jackson-module-http-query

It may be useful, although I suspect the object - map - query params trick is sufficient for most people's needs.

Upvotes: 0

Redlab
Redlab

Reputation: 3118

You could skip making the MultiValueMap and pass the params directly to the UriBuilder.

  uri = uriBuilder().path(RestResourcePaths.My_PATH);
 objectMapper.convertValue(myFilter, new TypeReference<Map<String,String>>() {})
 .forEach(uri::queryParam)

Upvotes: 9

Related Questions