我在这里寻找一些解决方案,我没有找到任何正确的答案给我的问题,所以我想问你。使用Spring控制器返回的jQuery和GSON解析JSON对象
我有一些简单的属性POJO。和另一个POJO列表。
public class Standard implements Serializable {
private String id;
private String title;
private String description;
private Set<Interpretation> interpretations = new LinkedHashSet<Interpretation>();
}
public class Interpretation implements Serializable {
private String id;
private String title;
private String description;
}
在我的控制器类中,我使用GSON返回Standard POJO。
@RequestMapping(value="/fillStandard", method= RequestMethod.GET)
public @ResponseBody String getStandard(@RequestParam String id) {
Standard s = DAOFactory.getInstance().getStandardDAO().findById(id);
return new Gson().toJson(s);
}
问题是,我能够使用jQuery获得标准POJO中的解释列表吗?喜欢的东西:
function newStandard() {
$.get("standard/fillStandard.htm", {id:"fe86742b2024"}, function(data) {
alert(data.interpretations[0].title);
});
}
非常感谢!
编辑: 好吧,感谢@Atticus,有我的问题的解决方案。希望它能帮助某人。
@RequestMapping(value="/fillStandard", method= RequestMethod.GET, produces="application/json")
public @ResponseBody Standard getStandard(@RequestParam String id) {
Standard s = DAOFactory.getInstance().getStandardDAO().findById(id);
return s;
}
使用@ResponseBody
允许你返回整个POJO,但你需要添加produces="application/json"
您@RequestMapping
注释。然后,您将能够像jQuery那样捕获jQuery中的返回对象。
function newStandard() {
$.get("standard/fillStandard.htm", {id:"idOfStandard"}, function(data) {
alert(data.id); //Standard id
alert(data.interpretations[0].title); //id of Interpretation on first place in array
});
我编辑了我的答案以控制jQuery代码。您必须创建一个包含您请求的数据的JSON对象。那么,这就是你如何发送你的数据(在服务器端),以便能够在客户端接收你需要的东西。 – Atticus
感谢您的回复:)我用你的代码,现在在jQuery alert(data.toString)返回{“handler”:{“interfaces”:[{}],“structured”:true,“persistentClass”:{}, “overridesEquals”:真 “的entityName”: “com.web.model.Standard”, “ID”: “fe86742b2024”, “目标”:{ “ID”: “fe86742b2024”, “称号”: “fe86742b2024”,”说明 “:” 递减”, “解释”:{ “ID”: “5f5c9dc31119”, “称号”: “5.2.4”, “说明”: “递减”}, “初始化”:真正}, “他人” :假,“解释”:[],“评论”:[]},我无法从中得到任何东西。既不data.id也不data.interpretations.id?我究竟做错了什么 ? – s0vet
出于某种原因,您的数据将被放入JSON答案的目标字段中,并且其他属性也会被序列化。如果不仔细查看代码,我不能说出问题所在。你可以发送给我(使用我的个人资料页面上的电子邮件地址)? – Atticus