Spring MVC @RequestBody接收具有非原始属性的Object包装器

时间:2013-10-31 10:08:33

标签: java json spring rest spring-mvc

我按如下方式创建JSON:

    var manager = {
        username: "admin",
        password: "admin"
    };
    var userToSubscribe = {
        username: "newuser",
        password: "newpassword",
        email: "user@1and1.es"
    };

    var openid = "myopenid";

    var subscription = {
            manager: manager,
            userToSubscribe : userToSubscribe,
            openid : openid
    };

    $.ajax({
        url: '/myapp/rest/subscribeUser.json',
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        mimeType: 'application/json',
        data: JSON.stringify({subscription : subscription})   
    });

这是发送的JSON:

{"subscription":{"manager":{"username":"admin","password":"admin"},"userToSubscribe":{"username":"newuser","password":"newpassword","email":"user@1and1.es"},"openid":"myopenid"}}  

我想把这个JSON映射到一个Wrapper类。这是包装器:

private class Subscription{
    private User manager;
    private User userToSubscribe;
    private String openid;
    public User getManager() {
        return manager;
    }
    public void setManager(User manager) {
        this.manager = manager;
    }
    public User getUserToSubscribe() {
        return userToSubscribe;
    }
    public void setUserToSubscribe(User userToSubscribe) {
        this.userToSubscribe = userToSubscribe;
    }
    public String getOpenid() {
        return openid;
    }
    public void setOpenid(String openid) {
        this.openid = openid;
    }
}

pom.xml中的jackson依赖项(我使用的是spring 3.1.0.RELEASE):

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.10</version>
    </dependency>

rest-servlet.xml中的映射

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
   <property name="messageConverters">
       <list>
           <ref bean="jsonConverter" />
       </list>
   </property>
</bean>

<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
   <property name="supportedMediaTypes" value="application/json" />
</bean>

控制器方法的标题:

public @ResponseBody SimpleMessage subscribeUser(@RequestBody Subscription subscription)

作为POST的结果,我收到400不正确的请求错误。是可以这样做还是我需要使用@RequestBody字符串或@RequestBody Map<String,Object>并自己解码JSON?

谢谢!

3 个答案:

答案 0 :(得分:12)

看着你的JSON

{
    "subscription": {
        "manager": {
            "username": "admin",
            "password": "admin"
        },
        "userToSubscribe": {
            "username": "newuser",
            "password": "newpassword",
            "email": "user@1and1.es"
        },
        "openid": "myopenid"
    }
}

根元素是subscription,它是一个JSON对象。您的Subscription课程没有subscription字段。因此,没有任何内容可以将subscription元素映射到它,因此它会因400 Bad Request而失败。

创建课程SubscriptionWrapper

public class SubscriptionWrapper {
    private Subscription subscription;

    public Subscription getSubscription() {
        return subscription;
    }

    public void setSubscription(Subscription subscription) {
        this.subscription = subscription;
    }
}

并更改您的处理程序方法以接受此类型的参数

public @ResponseBody SimpleMessage subscribeUser(@RequestBody SubscriptionWrapper subscriptionWrapper)

您可能需要在ObjectMapper中配置MappingJacksonHttpMessageConverter(您应该使用的MappingJackso2nHttpMessageConverter),以便忽略缺失的属性。

答案 1 :(得分:4)

我要回答我自己的问题。首先要特别感谢Sotirios Delimanolis,因为他给了我钥匙,以便调查它发生了什么。

如您所知,我从视图中创建了以下json:

{"manager":{"username":"admin","password":"admin"},"userToSubscribe":{"username":"newuser","password":"newpassword","email":"user@1and1.es"},"openid":"https://myopenid..."}

我稍微改变了一下,因为我意识到创建对象Subscription和var Subscription不是必需的。如果您像这样构建JSON,它将完美地运行:

var manager = {
    username: "admin",
    password: "admin"
};
var userToSubscribe = {
    username: "newuser",
    password: "newpassword",
    email: "user@1and1.es"
};

var openid = "https://myopenid...";

$.ajax({
    url: '/dp/rest/isUserSuscribed.json',
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    mimeType: 'application/json',
    data: JSON.stringify({manager : manager, userToSubscribe : userToSubscribe, openid : openid})   
});

控制器收到这个json:

@RequestMapping(method=RequestMethod.POST, value="/isUserSuscribed.json")
public @ResponseBody ResponseMessageElement<Boolean> isUserSuscribed(@RequestBody SubscriptionWrapper subscription){

SubscriptionWrapper ......

private static class SubscriptionWrapper {
    BasicUser manager;
    BasicUser userToSubscribe;
    String openid;

    public BasicUser getManager() {
        return manager;
    }
    public void setManager(BasicUser manager) {
        this.manager = manager;
    }
    public BasicUser getUserToSubscribe() {
        return userToSubscribe;
    }
    public void setUserToSubscribe(BasicUser userToSubscribe) {
        this.userToSubscribe = userToSubscribe;
    }
    public String getOpenid() {
        return openid;
    }
    public void setOpenid(String openid) {
        this.openid = openid;
    }
}

那么......问题是什么?我收到了错误的请求400错误...我调试了MappingJackson2HttpMessageConverter作为Sotirios建议并且有一个异常(没有合适的构造函数)。 Jackson Mapping无法构建内部类,无论此类是否不是静态的。将SubscriptionWrapper设置为static是解决我的问题的方法。

您还可以查看以下答案: http://stackoverflow.com/questions/8526333/jackson-error-no-suitable-constructor

http://stackoverflow.com/questions/12139380/how-to-convert-json-into-pojo-in-java-using-jackson

如果您有反序列化的问题,请检查: http://stackoverflow.com/questions/17400850/is-jackson-really-unable-to-deserialize-json-into-a-generic-type

感谢所有回复。

答案 2 :(得分:2)

您不需要自己做这件事。您需要在pom中添加此依赖项:

<dependencies>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.8.5</version>
    </dependency>
  </dependencies>

之后春天会为你做转换。