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?
let obj = { param1: 'something', param2: 'somethingelse', param3: 'another' } obj['param4'] = 'yetanother'; const url = new URL(`your_url.com`); url.search = new URLSearchParams(obj); const response = await fetch(url); Show activity on this post. Show activity on this post.
But anyway, if you want to send as query string you can do following: Convert object into string. Encode string. Append as parameter.
Create new map and put there parameters you need: Map<String, String> params = new HashMap<>(); params. put("param1", "value1"); params. put("param2", "value2");
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With