我有
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
SessionInfo register(UserProfile profileJson){
...
}
我通过这种方式传递 profileJson:
http://server/url?profileJson={"email": "mymail@gmail.com"}
但是我的 profileJson 对象的字段全部为空。我应该怎么做才能让 spring 解析我的 json?
最佳答案
这个问题的解决方案非常简单,几乎会让你发笑,但在我开始讨论之前,我首先要强调的是,没有一个有自尊心的 Java 开发人员永远不会在不使用 Jackson 高性能 JSON 库的情况下使用 JSON。
Jackson 不仅是 Java 开发人员的主力和事实上的 JSON 库,而且还提供了一整套 API 调用,使 JSON 与 Java 的集成变得轻而易举(您可以在 http://jackson.codehaus.org/ 下载 Jackson)。
现在就给出答案。假设您有一个如下所示的 UserProfile pojo:
public class UserProfile {
private String email;
// etc...
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
// more getters and setters...
}
...然后,用于转换 GET 参数名称“profileJson”且 JSON 值为 {"email": "mymail@gmail.com"} 的 Spring MVC 方法在 Controller 中将如下所示:
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper; // this is your lifesaver right here
//.. your controller class, blah blah blah
@RequestMapping(value="/register", method = RequestMethod.GET)
public SessionInfo register(@RequestParam("profileJson") String profileJson)
throws JsonMappingException, JsonParseException, IOException {
// now simply convert your JSON string into your UserProfile POJO
// using Jackson's ObjectMapper.readValue() method, whose first
// parameter your JSON parameter as String, and the second
// parameter is the POJO class.
UserProfile profile =
new ObjectMapper().readValue(profileJson, UserProfile.class);
System.out.println(profile.getEmail());
// rest of your code goes here.
}
嘭!你完成了。我鼓励您仔细阅读 Jackson API 的大部分内容,因为正如我所说,它是一个救星。例如,您是否从 Controller 返回 JSON?如果是这样,您需要做的就是在您的库中包含 JSON,并返回您的 POJO,Jackson 会自动将其转换为 JSON。没有比这更容易的了。干杯! :-)
关于java - Spring MVC Controller 中的 JSON 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40679736/