I would like to get a response from WebClient and convert it to just a Map without creating any Class for the response. Is it possible? So I would like something like this below. The code below is not a valid code, it is just an idea of what I want.
public Map<String, String> someFunction() {
return webClient.post()
.uri("/some/path")
.retrieve()
.bodyToFlux(HashMap.class)
.block();
If you're interested in saving a LOC, you may want to look at a core Spring Framework class: ParameterizedTypeReference<T>
, found here.
public Map<String, String> someFunction() {
return webClient.post()
.uri("/some/path")
.retrieve()
.bodyToFlux(new ParameterizedTypeReference<Map<String,String>>(){})
.block();
}
Cheers.
I would first try getting the response object into a String and also make sure I am accepting JSON type in return. Once I get the respone into a String, you can try using fasterxml's jackson databind library which can convert a JSON string into Hashmap.
For example
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"abc\", \"age\":25}";
Map<String, Object> map = new HashMap<String, Object>();
// convert JSON string to Map
map = mapper.readValue(json, new TypeReference<Map<String, String>>(){});
System.out.println(map);
Here is the databind library and core library java docs link
jackson-databind
jackson-core
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