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\"}
<
I have written a custom WebArgumentResolver that does exactly this, combined with a custom annotation.
I don't have the source available to me now, but basically I annotated my method like this:
@RequestMapping(value = "/path", method = RequestMethod.POST)
public void handleRequest(@JsonField("first") String first, @JsonField("second") String second) {
// ...
}
Then my JsonFieldWebArgumentResolver
checks if the method parameter is annotated with JsonField
, and if it is it extracts the actual type from the parameter (not quite straight-forward it turns out if you want to handle generic parameters as well, such as List<String>
or List<Pojo>
), and invokes Jackson's JsonParser manually to create the correct type. It's a shame I can't show you any code, but that's the gist of it.
However, that solution is for Spring MVC 3.0, and if you are using 3.1 I think you will be better off using a custom HandlerMethodArgumentResolver instead. But the idea should be the same.
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)