How can I easily separate JSON values that are sent in the same request?
Given that I POST a JSON to my server:
{"first":"A","second":"B"}
If I implement the following method in the Controller:
@RequestMapping(value = "/path", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public void handleRequest(@RequestBody String input) {
// ...
}
then the input
parameter will constitute a String with the entire JSON object, {"first":"A","second":"B"}
. What I really want is two separate Strings (or a String and an int whichever is suitable for the particular request) with just the two values (other key / value pairs that the client may send should be ignored).
If the strings were sent as request parameters instead of JSON request body it would be simple:
@RequestMapping(value = "/path", method = RequestMethod.POST)
public void handleRequest(@RequestParam("first") String first,
@RequestParam("second") String second) {
// ...
}
I know that I can create a simple bean class that can be used in conjunction with the @RequestBody
annotation that will contain both A
and B
when used, but it seems like a detour, since they will have different purposes inside the web app.
Dependencies: org.springframework : spring-web : 3.1.0.RELEASE org.codehaus.jackson : jackson-mapper-asl : 1.9.3
public class Input {
private String first;
private String second;
//getters/setters
}
...and then:
public void handleRequest(@RequestBody Input input)
In this case you need Jackson to be available on the CLASSPATH.
public void handleRequest(@RequestBody Map<String, String> input)
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