0

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<Comment> 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?

4
  • can it be an object with one element, {"comments":[...]} ? Commented Aug 10, 2011 at 15:38
  • return "\"comments\":" + gson.toJson(service.findNewComments(id,lastId)); ??? Commented Aug 10, 2011 at 15:38
  • Why does it have to have such a wrapper? That adds no real information in there, why not just return JSON array as is? Commented Aug 10, 2011 at 18:03
  • I only do it if the client code expects a particular format. Commented Aug 10, 2011 at 18:40

2 Answers 2

3

Not sure if this is acceptable to you but:

public class CommentWrapper {
    List<Comments> comments;
    public CommentWrapper(List<Comment> 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.

Sign up to request clarification or add additional context in comments.

4 Comments

Ye, thank you. I thought that there is some easier way, but it seems that it is the only one.
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.
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: I'm not a javascript expert you're probably better served by posting a new question.
0

Aside from wrapper object, you can also use a simple java.util.Map with single entry, possibly bit less code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.