How to convert object to query string in Java?
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();
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);
}