Create a specific JSON String with Gson

mybecks picture mybecks · Feb 8, 2012 · Viewed 10.4k times · Source

When I use JSON-Lib project, I can create with the command

JSONObject jObject = new JSONObject();
jObject.accumulate("articles", list);
String json = jObject.toString();

The following Output:

{
    "articles": [
        {
            "amount": "50",
            "id": "1",
            "pct": "50,00",
            "price": "162,37",
            "startamount": "100",
            "stockvalue": "8118,45"
        },
        {
            "amount": "20",
            "id": "2",
            "pct": "20,00",
            "price": "164,83",
            "startamount": "100",
            "stockvalue": "3296,60"
        },
        {
            "amount": "20",
            "id": "3",
            "pct": "20,00",
            "price": "170,40",
            "startamount": "100",
            "stockvalue": "3408,00"
        },...
]
}

Meanwhile I use the Gson project and are tied to it. But the following code:

Gson gson = new Gson();
String json = gson.toJson(list);

will give me this output:

[
    {
        "id": "1",
        "amount": "50",
        "startamount": "100",
        "pct": "50,00",
        "price": "162,37",
        "stockvalue": "8118,45"
    },
    {
        "id": "2",
        "amount": "20",
        "startamount": "100",
        "pct": "20,00",
        "price": "164,83",
        "stockvalue": "3296,60"
    },...]

The elements in my list are objects from my pojo article

public class Article implements IsSerializable {
    private String id;
        private String amount;
        private String startamount;
        private String pct;
        private String price;
        private String stockvalue;

        public Article(){

        }

        //Setter & Getter
}

How can I create with the help of Gson a JSON string like the one JSON-Lib will create (JSONObject with JSONArray which inlcudes JSONObjects). In future the JSON String will/must be extended with more arrays (not articles, but other stuff).

I retrieve this generated JSON String from a HttpServlet. Does it make sense to deserialize the Gson JSON String back to ArrayList or should I use the GWT JavaScript Overlay Types?

Thanks & BR, mybecks

Answer

jusio picture jusio · Feb 8, 2012

It happens because you give to the Gson a list of objects. So if you want to have the same output as in first json snippet, you have to define object, which will hold the list of articles. E.g. :

public class ArticlesResult {
   private List<Article> articles;


   ...//the rest of the code, like getters and setters
}

Regarding converting JsArray back to the ArrayList. It depends, most of the times it is better to use overlay types, since they are faster to create, and have small footprint in generated JS code. But it is true only for production mode. In devmode, overlay types are slower, so if you rapidly access overlay types, you will waste a lot of time there.