@JsonProperty not working for Content-Type : application/x-www-form-urlencoded

后端 未结 2 594
温柔的废话
温柔的废话 2021-01-19 14:55

The REST API takes input content type : application/x-www-form-urlencoded, when it is mapped to a Java Object, like

 public class MyRequest {

    @JsonPrope         


        
2条回答
  •  庸人自扰
    2021-01-19 15:56

    I had the same problem recently using SpringMVC and Jackson!

    In Spring, when you explicit configure your endpoint to consume only application/x-www-form-urlencoded requests Spring is able to serialize into your POJO classes but it does not use Jackson because it isn't JSON.

    So, in order to get those Jackson annotations working using your POJO, you'll have to:

    1. Get your data as a map
    2. Parse your data map with Jackson's ObjectMapper

    In my case, with Spring I could resolve this problem with the following code:

    @RequestMapping(
            value = "/rest/sth",
            method = RequestMethod.POST
    )
    public ResponseEntity create(@RequestBody MultiValueMap paramMap) { ... }
    

    When you remove the "consumes" attribute from @RequestMapping annotation you have to use @RequestBody or else Spring won't be able to identify your map as a valid parameter.

    One thing that you'll probably notice is that MultiValueMap is not a regular map. Each element value is a LinkedList because http form data can repeat values and therefore those values would be added to that linked list.

    With that in mind, here is a simple code to get the first element and create another map to convert to your POJO:

        HashMap newMap = new HashMap<>();
        Arrays.asList(new String[]{"my_name", "my_phone"})
                .forEach( k -> newMap.put(k, ((List) paramMap.get(k)).get(0)));
    
        MyRequest myrequest = new ObjectMapper().convertValue(newMap, MyRequest.class);
    

    I hope it can help you how it helped me :)

提交回复
热议问题