How to convert object to query string in Java?

dev :

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?

Andreas :

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();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=83131&siteId=1