Spring 3 MVC - 使用域对象作为@RequestBody
我正在考虑使用域对象作为@RequestBody。我的域对象是不可变的对象,因此它们没有任何 setter 方法。它是一个 application/json 请求,我正在使用 Jackson 消息转换器。
@RequestMapping(value="/user", method=RequestMethod.POST)
@ResponseStatus(HttpStatus.NO_CONTENT)
public @ResponseBody void createUser(@RequestBody User user) {
..........
}
由于我的用户对象中没有 setter 方法,因此当我向“/user”发出 POST 请求时,我从 MappingJacksonHttpMessageConverter 收到 UnrecognizedPropertyException。在 spring 中是否有一种方法可以使用用户对象的静态工厂方法(或构造函数)而不是设置器来分配数据。
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 factory method(or constructor) of user object instead of setters.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我自己找到了答案。使用@JsonCreator。这是一个例子。您也可以在静态工厂方法上使用它。
I found the answer myself. Use @JsonCreator. Here is an example. You can use it on static factory methods as well.
我认为这取决于你的 JSON 解析器。我知道 GSON[1] 适用于字段(而不是 getter/setter),所以使用它可能会更幸运。我相信您必须编写自己的消息转换器。
[1] http://code.google.com/p/google-gson/
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/