Spring MVC, deserialize single JSON?

前端 未结 2 849
南笙
南笙 2021-01-05 06:09

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\"}
<         


        
相关标签:
2条回答
  • 2021-01-05 06:49

    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.

    0 讨论(0)
  • 2021-01-05 07:01

    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)
    
    0 讨论(0)
提交回复
热议问题