Up vote 0 down vote favorite share g+ share fb share tw.
I am using GSON library. I have a programm which returns JSON. JSON constructs and returns in this way: Gson gson = new Gson(); //findNewComments returns List comments return gson.
ToJson(service. FindNewComments(id,lastId)); So the result is: { "id": 43, "entryId": 19, "author": " m8w46", "body": "mw86", "date": "WED 9, 2011" }, { "id": 44, "entryId": 19, "author": " n7w4", "body": "nw77w4", "date": "WED 9, 2011" } But this array must be named as "comments"! "comments": { "id": 43, "entryId": 19, "author": " m8w46", "body": "mw86", "date": "WED 9, 2011" }, { "id": 44, "entryId": 19, "author": " n7w4", "body": "nw77w4", "date": "WED 9, 2011" } How can I do that?
Java json servlets return gson link|improve this question asked Aug 10 '11 at 15:35Lomer2815 88% accept rate.
– Kevin Aug 10 '11 at 15:38 return "\"comments\":" + gson. ToJson(service. FindNewComments(id,lastId));?
– SJuan76 Aug 10 '11 at 15:38 @SJuan76 doesn't work – Lomer Aug 10 '11 at 15:44 Why does it have to have such a wrapper? That adds no real information in there, why not just return JSON array as is? – StaxMan Aug 10 '11 at 18:03 I only do it if the client code expects a particular format.
– Kevin Aug 10 '11 at 18:40.
Not sure if this is acceptable to you but: public class CommentWrapper { List comments; public CommentWrapper(List comments) { this. Comments = comments; } } Then you can do: return new Gson(). ToJson(new CommentWrapper(service.
FindNewComments(id,lastId))); Which results in: { "comments": ....your data here... } Not sure if the object syntax is acceptable to you or not.
Ye, thank you. I thought that there is some easier way, but it seems that it is the only one. – Lomer Aug 10 '11 at 15:49 1 I usually make the wrapper class an inner class of whatever controller/servlet I'm working in, because typically it has no use outside that.
– Kevin Aug 10 '11 at 16:00 Can I ask one more question? I am trying to show elements of this array with javascript, but it says, that they are undefined, but the cycle works fine!. What am I doing: var json = eval("("+xmlhttp.
ResponseText+")"); for(var comment in json. Comments){alert(comment. Author);} – Lomer Aug 10 '11 at 17:58 @Lomer: I'm not a javascript expert you're probably better served by posting a new question.
– Kevin Aug 10 '11 at 18:41.
Aside from wrapper object, you can also use a simple java.util. Map with single entry, possibly bit less code.
I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.