5

For example, here's a Get request:

get: /search?product_category=1&user_name=obama

I want to define a SearchRequest to accept the query string, so I can use JSR 303 bean validation annotations to validate parameters, like below:

public class SearchRequest {
    @NotEmpty(message="product category is empty")
    private int productCategory;
    @NotEmpty(message="user name is empty")
    private int userName;
}

So, is there something like @JsonProperty in jackson to convert underscore style to camel style?

pat.inside
  • 1,724
  • 4
  • 17
  • 25
  • Are you looking for http://stackoverflow.com/questions/10519265/jackson-overcoming-underscores-in-favor-of-camel-case? – Sanghyun Lee May 15 '15 at 05:02
  • @Sangdol No, that's for parsing json into javabean, however what I want is parsing query string into javabean. – pat.inside May 15 '15 at 05:29

2 Answers2

1

You only have two options;

First. Have your SearchRequest pojo with annotated values for validation but have a controller POST method receive the pojo as request body as a JSON/XML format.

public class SearchRequest {
    @NotEmpty(message="product category is empty")
    private int productCategory;
    @NotEmpty(message="user name is empty")
    private int userName;
}

public String search(@RequestBody @Valid SearchRequest search) {
    ...
}

Second. Have validations in the Controller method signature itself eliminating validations in the pojo but you can still use the pojo if you want.

public class SearchRequest {

    private int productCategory;

    private int userName;
}

public String search(@RequestParam("product_category") @NotEmpty(message="product category is empty") String productCategory, @RequestParam("user_name") @NotEmpty(message="user name is empty") String username) {
    ... // Code to set the productCategory and username to SearchRequest pojo.
}
shazin
  • 21,379
  • 3
  • 54
  • 71
0

IMHO, the simplest way would be to use additional getters and setters. It is indeed code duplication, but so trivial that I find it harmless :

public class SearchRequest {
    private int productCategory;
    private String userName;
    @NotNull(message="product category is empty")
    public int getProduct_category() {
        return getProduct_category();
    }
    @NotEmpty(message="user name is empty")
    public String getUser_name() {
        return userName;
    }
    public void setProduct_category(int product_category) {
        productCategory = product_category;
    }
    public void setUser_name(String user_name) {
        userName = user_name;
    }
}

BTW, I assumed that userName should better be a String and that for an integer property you wanted actually @NotNull ...

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252