Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

 public class MyRequest {

    @JsonProperty("my_name")
    private String myName;

    @JsonProperty("my_phone")
    private String myPhone;

    //Getters and Setters of myName and myPhone.

    }

In form input request, I am setting values of my_name and my_phone but the MyRequest object comes with myName and myPhone as null.

I am using Jackson-annotations 2.3 jar

Any Suggestions what may be wrong ?

like image 380
Vineet Singla Avatar asked Feb 06 '23 10:02

Vineet Singla


1 Answers

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<String> 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<String, Object> 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 :)

like image 72
Sidharta Noleto Avatar answered May 02 '23 05:05

Sidharta Noleto