通过POST和SPRING-MVC发送多个对象时出现问题
我正在开发必须接收多个信息的REST服务。在这种情况下,有两个对象和一个属性。
这是我测试POST请求的javascript
var user = { username: "admin",
password: "admin"
};
var userToSubscribe = {
username: "newuser",
password: "newpassword",
email: "user@1and1.es"
};
var openid = "myopenid";
$.ajax({
url: '/myportal/rest/subscribeUser.json',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
data: JSON.stringify({ user: user, userToSubscribe: userToSubscribe, openid: openid})
});
POST请求:
JSON openid
"myopenid"
user
Object { username="admin", password="admin"}
userToSubscribe
Object { username="newuser", password="newpassword", email="user@1and1.es"}
Source
{"user":{"username":"admin","password":"admin"},"userToSubscribe":{"username":"newuser","password":"newpassword","email":"user@1and1.es"},"openid":"myopenid"}
以及处理POST的控制器:
@RequestMapping(method=RequestMethod.POST, value="/subscribeUser.json")public @ResponseBody Message subscribeUser(@RequestBody("user") User user, @RequestBody("userToSubscribe") User userToSubscribe, @RequestParam String openid){
...
}
错误是
POST subscriptionUser.json 400错误的请求localhost:8080 990 B [:: 1]:8080
我究竟做错了什么?
谢谢
回答:
请求主体将包含整个JSON内容。因此,当您要映射JSON时,仅使用一个RequestBody带注释的参数。您将必须执行以下操作:
public @ResponseBody Message subscribeUser(@RequestBody String str)ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(str);
然后使用映射器的convertValue方法从字符串中获取不同的对象。
JsonNode node = mapper.readTree(str);User theUser = mapper.convertValue(node.get("user"), User.class);
对于其他对象类似
以上是 通过POST和SPRING-MVC发送多个对象时出现问题 的全部内容, 来源链接: utcz.com/qa/400480.html