Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC, deserialize single JSON?

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

like image 636
matsev Avatar asked Jan 20 '12 18:01

matsev


1 Answers

POJO

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.

Map

public void handleRequest(@RequestBody Map<String, String> input)
like image 164
Tomasz Nurkiewicz Avatar answered Oct 22 '22 15:10

Tomasz Nurkiewicz