5

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.

Dima
  • 1,774
  • 5
  • 21
  • 31

3 Answers3

9
// 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();
BartoszMiller
  • 1,245
  • 1
  • 15
  • 24
1

use com.sun.jersey.api.client.Client:

Client.create().resource("url").queryParam(key, value).get()
shem
  • 4,686
  • 2
  • 32
  • 43
0
  1. convert an Object to a Map
  2. Convert Map to QueryString
package util;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Map;

public class ObjectConvertUtil {
    // convert Object to queryString 
    public static String toQS(Object object){

        // Object --> map
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> map =
                objectMapper.convertValue(
                        object, Map.class);


        StringBuilder qs = new StringBuilder();
        for (String key : map.keySet()){

            if (map.get(key) == null){
                continue;
            }
            // key=value&
            qs.append(key);
            qs.append("=");
            qs.append(map.get(key));
            qs.append("&");
        }

        // delete last '&'
        if (qs.length() != 0) {
            qs.deleteCharAt(qs.length() - 1);
        }
        return qs.toString();
    }
}

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>
Shuai Li
  • 2,426
  • 4
  • 24
  • 43