Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert object to query string in Java?

Tags:

java

junit

spring

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?

like image 295
dev Avatar asked Sep 25 '18 21:09

dev


People also ask

How do you serialize an object into a list of URL query parameters?

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.

Can we send object in query string C#?

But anyway, if you want to send as query string you can do following: Convert object into string. Encode string. Append as parameter.

How do I pass a query param on a map?

Create new map and put there parameters you need: Map<String, String> params = new HashMap<>(); params. put("param1", "value1"); params. put("param2", "value2");


1 Answers

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();
like image 173
Andreas Avatar answered Oct 12 '22 21:10

Andreas