通过POST和SPRING-MVC发送多个对象时出现问题 [英] Problems sending multiple objects through POST and SPRING-MVC

查看:217
本文介绍了通过POST和SPRING-MVC发送多个对象时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发必须接收多个信息的REST服务.在这种情况下,有两个对象和一个属性.

I'm developing REST services which have to receive multiple info. In this case, two objects and an attribute.

这是我正在测试POST请求的javascript

This is the javascript where I'm testing the POST request

    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的控制器:

And the controller which handles the 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

POST subscribeUser.json 400 Incorrect request localhost:8080 990 B [::1]:8080

我在做什么错了?

谢谢

推荐答案

请求正文将包含整个JSON内容.因此,当您要映射JSON时,仅使用一个RequestBody带注释的参数.您将必须执行以下操作:

The request body will contain the entire JSON content. So when you want to map the JSON, you use only one RequestBody annotated-parameter. You will have to do something like this:

public @ResponseBody Message subscribeUser(@RequestBody String str)
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(str);

然后使用映射器的convertValue方法从字符串中获取不同的对象.

And then use the convertValue method of the mapper to get your different objects from the string.

JsonNode node = mapper.readTree(str);
User theUser = mapper.convertValue(node.get("user"), User.class);

对于其他对象

这篇关于通过POST和SPRING-MVC发送多个对象时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆