我有
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
SessionInfo register(UserProfile profileJson){
...
}
我这样传递profileJson:
http://server/url?profileJson={"email": "mymail@gmail.com"}
但我的 profileJson 对象具有所有空字段。我应该怎么做才能让spring解析我的json?
最佳答案
解决这个问题的方法非常简单,实际上会让你发笑,但在我开始之前,让我先强调一下,任何有自尊的 Java 开发人员都不会,我的意思是永远在不使用 JSON 的情况下工作Jackson 高性能 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...
}
...然后您的 Spring MVC 方法将 GET 参数名称“profileJson”转换为 JSON 值为 {"email": "mymail@gmail.com"} 在您的 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。没有比这更容易的了。干杯! :-)
https://stackoverflow.com/questions/21577782/