开发者

Spring 3 MVC - using domain objects as @RequestBody

开发者 https://www.devze.com 2023-04-12 03:11 出处:网络
I am thinking of using domain object as @RequestBody. My domain objects are immutable objects and so they do not have any setter methods. Its a application/json request and I am using Jackson message

I am thinking of using domain object as @RequestBody. My domain objects are immutable objects and so they do not have any setter methods. Its a application/json request and I am using Jackson message converter.

@RequestMapping(value="/user", method=RequestMethod.POST)
@ResponseStatus(HttpStatus.NO_CONTENT)
public @ResponseBody void createUser(@RequestBody User user) {
    .......... 
}

Since I do not have setter methods inside my user object, when I do a POST request to "/user", I get UnrecognizedPropertyException from MappingJacksonHttpMessageConverter. Is there a way in spring in which I would be able to assign data using a static fa开发者_如何学编程ctory method(or constructor) of user object instead of setters.


I found the answer myself. Use @JsonCreator. Here is an example. You can use it on static factory methods as well.

@JsonCreator
public NonDefaultBean(@JsonProperty("name") String name, @JsonProperty("age") int age)
{
  this.name = name;
  this.age = age;
}


I think this is up to your JSON parser. I know that GSON[1] works on fields (as opposed to getters/setters), so you may have better luck using that. You'll have to writer your own message converter, I believe.

[1] http://code.google.com/p/google-gson/

0

精彩评论

暂无评论...
验证码 换一张
取 消