I have a URL abc.com/loc/lat=90.6&long=44.6&sf='random' here lat and long are required and sf is an optional param. I have created a class with these three as data members, how can I deserialize those params into that class object?
-
Does this answer your question? [Spring MVC: Complex object as GET @RequestParam](https://stackoverflow.com/questions/16942193/spring-mvc-complex-object-as-get-requestparam) – kvbx Mar 18 '21 at 22:10
1 Answers
SpringMVC will do that 'mapping' for you.
Look at the following piece of code.
There is a REST controller with one method. It expects the Request object. This object has three fields, just like you need. All of your street parameters will be mapped to the object fields automatically.
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/loc")
public @ResponseBody
Request myAction(Request reqObject) {
System.out.println("reqObject = " + reqObject);
return reqObject;
}
}
class Request {
float lat;
float longt;
String sf;
public float getLat() {
return lat;
}
public void setLat(float lat) {
this.lat = lat;
}
public float getLong() {
return longt;
}
public void setLong(float longt) {
this.longt = longt;
}
public String getSf() {
return sf;
}
public void setSf(String sf) {
this.sf = sf;
}
@Override
public String toString() {
return "Request{" +
"lat=" + lat +
", longt=" + longt +
", sf='" + sf + '\'' +
'}';
}
}
How to call it:
http://localhost:8080/loc?lat=90.6&long=44.6&sf=random
This is what you will get printed out:
{"lat":90.6,"sf":"random","long":44.6}
Try this out.
Note, how I had to name your long variable differently, this is because long is a reserved keyword in Java. We can't use it for a variable name. But we can define getters and setters in a way we like. getLong and setLong allow us to map 'long' parameter to the variable we need.
------------ Version of POJO class for Lombock lovers:
@Data
@ToString
class Request {
@NonNull
float lat;
@NonNull
float longt;
String sf;
}
With Lombok adding its magic, I have not found a way to handle your long input parameter. I suggest you to change it to 'longt' to make it work.
You will be calling your service like this:
http://localhost:8080/loc?lat=90.6&longt=44.6&sf=random

- 867
- 6
- 13
-
Hey thanks for response, I am using lombok, with non null annotations, where should I put the checks such that on and lat a can never be null? – Aman Saxena Mar 19 '21 at 01:14
-
I see, I like Lombok, let me update my answer. Please, do not forget to 'like' it :) – Igor Kanshyn Mar 19 '21 at 01:29
-
I have changed my variable name, now suppose if someone hit URL with wrong spelling if param, what will happen? – Aman Saxena Mar 19 '21 at 06:15
-
-
If a request is not correct, you will get an error response. Try that out – Igor Kanshyn Mar 21 '21 at 02:25