Search code examples
javajsongsonmustache

How to name an array of JSON objects using GSON?


I'm using gson library and Mustach.js template engine. I'm passing Collection of Products to jsp page.

Now i'm using the following code:

Collection<Product> products = productDAO.findAll();
    Gson gson = new Gson();
    JsonElement element = gson.toJsonTree(products,
            new TypeToken<Collection<Product>>() {
            }.getType());
    JsonArray jsonArray = element.getAsJsonArray();
    HttpServletResponse response = ServletActionContext.getResponse();
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    PrintWriter writer = response.getWriter();
    writer.print(jsonArray);

it generates following json output:

[{"name":"Ut Nisi A PC","price":1133.43,"storeId":1,"id":2},
{"name":"Ipsum Dolor Sit Company","price":967.45,"storeId":1,"id":3},
{"name":"Ligula Limited","price":156.66,"storeId":1,"id":100}]

What I want is to name an array:

 {
    "products": 
    [{"name":"Ut Nisi A PC","price":1133.43,"storeId":1,"id":2},
    {"name":"Ipsum Dolor Sit Company","price":967.45,"storeId":1,"id":3},
    {"name":"Ligula Limited","price":156.66,"storeId":1,"id":100}]}

So then in jsp for Mustache.js template I can refer to array like:

   <div id="container"></div> 

    <script id="products-template" type="text/mustache-template">
        {{#products}}
            <li>{{name}},{{price}}</li>
        {{/products}}
    </script>
    $.ajax({
            type : 'GET',
            dataType : 'json',
            url : 'product/upload_products',
            success : function(products) {
                var template = $('#products-template').html();
                var info = Mustache.render(template, products);
                $('#container').html(info);
            }
        })
    </script>

How using GSON library such output can be achieved ?


Solution

  • Simply create a new JsonObject and add a field

    JsonObject object = new JsonObject();
    object.add("products", jsonArray);
    

    then write that object to the response.