Server side I have this Java:
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("application/json;charset=UTF-8");
resp.setHeader("Cache-Control", "no-cache");
PersistenceManager pm = PMF.get().getPersistenceManager();
Extent<Video> extent = pm.getExtent(Video.class, false);
ArrayList<Video> list = new ArrayList<Video>();
for (Video e : extent) {
list.add(e);
}
Gson gson = new Gson();
String json = gson.toJson(list);
System.out.println(json); // As expected: [{"id":34,"title":"a title","videoUrl":"an.mp4","imageUrl":"a.jpg" etc.
resp.getWriter().write(json);
extent.closeAll();
pm.close();
}
Client side I have this JavaScript using jQuery:
var getAllRequest = $.ajax({
url: "http://localhost:8888/getAll",
type: "GET",
dataType: "json"
});
getAllRequest.done(function(response) {
alert (response) // THIS IS AN OBJECT ARRAY, i.e., [object Object],[object Object] etc.
});
My question: is response really a json object, or just an array of json objects.
I’m using jq grid, and it does not fill in the grid when given the response. (Feeding the response to the jq grid not shown here.)
JSON gives you the way to post information about the object as string. So there are no “json object”. Either you have string with for example the text like
or you have an object for example
The full specification of JSON is described here or in rfc4627. So you should not mix the initialization syntax which allows you to create object with the JSON string with very close syntax.
If you use $.ajax with
dataType: "json"parameter and the server response contains JSON string jqGrid internally convert the server response to object (see $.parseJSON function) and the parameter of thedonewill be already object. So you could usefor example inside of callback function of
getAllRequest.done. In any way the client seems to get correctly the server response.