1

I want implement a web-service which consumes only one named parameter in request-payload. In curl view it should be smth like: curl -X PATCH myurl.net/my_service -d "{mySingleParameter: 49}"

I'm trying to do it with Spring, but I wondered that to map such payload to my method I must to declare a new class. Like:

...
public static class PayloadWithSingleParamMSP{
  public Long mySingleParameter;
}

@RequestMapping(value = "my_service", method = RequestMethod.PATCH)
public String myService(@RequestBody PayloadWithSingleParamMSP payload){
  Long valueWhichIReallyNeed = payload.mySingleParameter;
  //do job
  ...
}
...

But is there a way to take value which I really need (mySingleParameter) directly?

Ivan Zelenskyy
  • 630
  • 7
  • 24

1 Answers1

3

You have couple options:

    @RequestMapping(value = "my_service", method = RequestMethod.PATCH)
    public String myService(@RequestBody ObjectNode payload){
        Long valueWhichIReallyNeed = payload.get("mySingleParameter").asLong();
        //do job
       ...
    }

or

@RequestMapping(value = "my_service", method = RequestMethod.PATCH)
public String myService(@RequestBody Map<String, String> payload){
    Long valueWhichIReallyNeed = Long.parseLong(payload.get("mySingleParameter"));
    //do job
    ...
}

or even

@RequestMapping(value = "my_service", method = RequestMethod.PATCH)
public String myService(@RequestBody  Long mySingleParameter){
    Long valueWhichIReallyNeed = mySingleParameter;
    //do job
    //  ...
}

but in this last case your curl will look following:

curl -X PATCH myurl.net/my_service -d "49" 

In answers for this question you can find more options: Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

Community
  • 1
  • 1
reynev
  • 308
  • 2
  • 5