Reputation: 4084
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 ?
Upvotes: 2
Views: 4689
Reputation: 109
Use JsonObject. So,
JsonObject jsonObject = new JsonObject();
jsonObject.add("products", jsonArray); // jsonObject has the add method not put.
Upvotes: 0
Reputation: 3972
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);
Upvotes: 0
Reputation: 280102
Simply create a new JsonObject
and add a field
JsonObject object = new JsonObject();
object.add("products", jsonArray);
then write that object to the response.
Upvotes: 3