简体   繁体   中英

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 ?

Simply create a new JsonObject and add a field

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

then write that object to the response.

Use JsonObject. So,

JsonObject jsonObject = new JsonObject();
jsonObject.add("products", jsonArray); // jsonObject has the add method not put.

The key of a Json Object is always a String but the value can be a String, a boolean, a number, a json array, ....

If you have an object that is an array you only need to pass it to a jsonObject in the value and create a String key.

Manage the jsonObject like an HashMap. To do what you need make a put("products", yourJsonArrayObject) in a new Json Object.

JsonObject yourNewObject = new JsonObject();
yourNewObject.put("products", yourJsonArrayObject);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM