@JsonProperty not working for Content-Type : appli

2019-02-25 13:31发布

问题:

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 ?

回答1:

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 :)



回答2:

I think that the very simple solution, is to have a setter related to the variables with "_".

public class MyRequest {

    @JsonProperty("my_name")
    private String myName;

    @JsonProperty("my_phone")
    private String myPhone;

    //Getters and Setters of myName and myPhone.

    //Setters for application/x-www-form-urlencoded
    public void setMy_name(String name) {
        setMyName(name);
    }
    ......
}

There are more solutions. See the link.