我按如下方式创建 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 Incorrect request 错误。是否有可能做到这一点,或者我需要用@RequestBody
String 来做,还是@RequestBody Map<String,Object>
自己解码 JSON?
谢谢!