开发者

How to construct objects and related objects from JSON request using Spring

I'm POSTing a JSON request to a Spring 3.0 controller. The method signature is...

@RequestMapping(value="/add", method=RequestMethod.POST)
public @ResponseBody Map<String, ? extends Object> add(@RequestBody Entry)

The JSON looks like this...

{"user":"1"}

The Entry object has one attribute of type User.

When a request is submitted this error is thrown,

org.codehaus.jackson.map.JsonMappingException: Can not construct instance of com.x.y.z.Entry, problem: no suitable creator method found

I'm guessing the error is due to the fact that user on Entry is of type User rather than S开发者_运维技巧tring ("1" is being passed in on the JSON).

Is there a way of taking the "1" coming in and using it to create a real User object (by looking it up in the database in this case)?


Does Entry have a parameterless constructor?

That's your first place to look. Normally errors of this nature occur because the code is looking for a parameterless constructor to create Entry with.

Your idea, that is to create User as the real user is fine, but it should be done after this method is called, in some other layer or something. You wanna keep things simple by not interfering with the marshalling of the json. You can add onto this with another layer.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜