I was looking for some solution around here and I didnt find any correct answer to my question so I would like to ask you.
I have POJO with some simple attribs. and one List of another POJOs.
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;
}
In my controller class, I am returning Standard POJO with GSON.
@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);
}
The question is, am I able to get the list of interpretations in my Standard POJO using jQuery ? Something like :
function newStandard() {
$.get("standard/fillStandard.htm", {id:"fe86742b2024"}, function(data) {
alert(data.interpretations[0].title);
});
}
Thanks a lot !
EDIT:
Well, thanks to @Atticus, there is solution of my problem. Hope that it will help somebody.
@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;
}
Using @ResponseBody allows you to return the whole POJO, but you need to add produces="application/json" to your @RequestMapping annotation. Then you will be able to catch a returning object as JSON in jQuery like as I supposed.
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
});
Well you have to create and register your custom serializer.
It goes like this:
Your serializer looks like this:
In this case your Json would look something like:
Now, you can access your data with
jQuerylike this:I hope this helps.
EDIT:
I see that your response gets converted to the declared method argument type which is
String(as stated here: 16.3.3.2 Supported method return types). But what you really want is yourStandradPOJO converted to JSON. I am not very familiar with Spring but as I have read here (16.3.2.6 Producible Media Types) there is another, maybe easier solution. If you want to return a JSON object, then change the return type of thegetStandardmethod toStandardinstead ofStringand addproduces="application/json"to your@RequestMappingannotation. As far as I have read this should tellSpringthat the return type should be converted to JSON. In this case you do not need to useGson.