1

Is there any direct method to convert the HTTP request parameters to an object? (something like object mapper)

For example, if the request http://localhot:8080/users/id=5&name=10 httpHandler() then id=5&name=10 this needs to converted to User object

public class User {
         int id;
         String name;
         //getters and setters
}

class MyHandler implements HttpHandler {
   @Override
   public void Handle(HttpExchange http) {
   String param = http.get.getRequestURI().getQuery();
   ?? // how to map it to the User Object?
   }
}
Shiny
  • 161
  • 1
  • 1
  • 9

2 Answers2

0

Spring does this for you automatically with RequestBody annotation.

Say you make an HTTP POST request to URL http://localhost:8080/users/ with JSON request

{
  id: 1,
  name: "Bob"
}

You can map this request using Spring like so:

@POST
@Path("/users")
@Consumes(MediaType.APPLICATION_JSON)
public String users(@RequestBody User user) {
    // Value is "ID: 1, Name: Bob"
    return "ID: " + user.getId() + ", Name: " + user.getName();
}
Justifyz
  • 21
  • 3
0

If you are using Spring then Here is a very good example. You can annotate controller method with @GetMapping and pass a DTO object(that have all your request params as members) to method as an argument.

Spinner
  • 11
  • 2