您可能需要手动解析JSON字符串并将其写入响应才能为您工作。我建议使用jackson2 API。
https://github.com/FasterXML/jackson
首先,接受JSON字符串作为从请求中的参数,然后手动分析字符串和从使用杰克逊ObjectMapper一个POJO。
这里的jQuery的/ JavaScript的:
function incrementAge(){
var person = {name:"Hubert",age:32};
$.ajax({
dataType: "json",
url: "/myapp/MyAction",
type: "POST",
data: {
person: JSON.stringify(person)
}
})
.done(function (response, textStatus, jqXHR) {
alert(response.name);//Hubert
alert(response.age);//33
//Do stuff here
});
}
的人POJO:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
//Allows name or age to be null or empty, which I like to do to make things easier on the JavaScript side
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
而这里的控制器:
import com.fasterxml.jackson.databind.ObjectMapper;
/*snip*/
@Controller
public class MyController{
//I prefer to have a single instance of the mapper and then inject it using Spring autowiring
private ObjectMapper mapper;
@Autowired
public MyController(ObjectMapper objectMapper){
this.objectMapper = objectMapper;
}
@RequestMapping(value="/myapp/MyAction", method= {RequestMethod.POST})
public void myAction(@RequestParam(value = "person") String json,
HttpServletResponse response) throws IOException {
Person pojo = objectMapper.readValue(new StringReader(json), Person.class);
int age = pojo.getAge();
age++;
pojo.setAge(age);
objectMapper.writeValue(response.getOutputStream(),pojo);
}
}