Reputation: 451
I am trying to convert the following object to query string, so that can be used with GET request.
Class A {
String prop1;
String prop2;
Date date1;
Date date2;
ClassB objB;
}
Class B {
String prop3;
String prop4;
}
We can do that first object to Map then convert map to MultiValueMap and use URIComponentsBuilder.fromHttpUrl("httpL//example.com").queryParams(multiValueMap).build();
Is there shorter and better way of converting object to query string so that be used with GET request in Spring Project for Junit Test?
Upvotes: 8
Views: 16322
Reputation: 6963
This is how i would do it,
Create Map, populate and then iterate over map items and append to builder this seems to be working for me. It does not cover support for nested objects. Should be simple with recursion.
public String getRequestString(Class clazz, Object o) {
StringBuilder queryStringBuilder = new StringBuilder();
final Map<String, String> queryParams = new LinkedHashMap<>();
try {
for (Field f : clazz.getDeclaredFields()) {
f.setAccessible(true);
queryParams.put(f.getName(), String.valueOf(f.get(o)));
}
for (Map.Entry<String, String> entry : queryParams.entrySet()) {
queryStringBuilder.append(testStringUtils.toSnakeCase(entry.getKey()));
queryStringBuilder.append("=");
queryStringBuilder.append(entry.getValue());
queryStringBuilder.append("&");
}
logger.info("Map: " + queryParams);
} catch (Exception e) {
e.printStackTrace();
}
final String queryString = queryStringBuilder.toString();
logger.info("Query string : " + queryString.substring(0, queryString.length() - 1));
return "?" + queryString.substring(0, queryString.length() - 1);
Upvotes: 0
Reputation: 719
You could write your own method that uses java.lang.reflect
. Here's an example
public static String getRequestString(String urlString, Class clazz, Object o){
String queryString = "?";
try {
for (Field f : clazz.getDeclaredFields()) {
f.setAccessible(true);
queryString += queryString.concat(f.getName() + "=" + String.valueOf(f.get(o)) + "&");
}
}catch (Exception e){
e.printStackTrace();
}
return urlString + queryString.substring(0,queryString.length()-1);
}
Upvotes: 3
Reputation: 331
OpenFeign has the annotation @QueryMap
to generate query params dinamicaly based on a object attributes:
public interface Api {
@RequestLine("GET /find")
V find(@QueryMap CustomPojo customPojo);
}
See more at: https://github.com/OpenFeign/feign#dynamic-query-parameters
Upvotes: 1
Reputation: 159086
Why convert to Map
then MultiValueMap
, instead of just building it directly?
DateFormat dateFmt = new SimpleDateFormat("whatever date format you want");
URIComponentsBuilder.fromHttpUrl("httpL//example.com")
.queryParam("prop1", a.prop1)
.queryParam("prop2", a.prop2)
.queryParam("date1", dateFmt.format(a.date1))
.queryParam("date2", dateFmt.format(a.date2))
.queryParam("prop3", a.objB.prop3)
.queryParam("prop4", a.objB.prop4)
.build();
Upvotes: 3