Question

I'd like to build a json in ways of:

{"total":1,"rows":[{"id":1,"name":"Chai","price":18.00}],"footer":[{"name":"Total","price":18.00}]}

This example was obtained from: http://www.jeasyui.com/tutorial/datagrid/datagrid17.php

It's mandatory that I have a "total" property with some value and a "rows" property with a collection refering to it, exactly as in the example above.

Consider that for "rows" property actually I have a set of java Properties class objects, inside a List<Properties> collection, with value pairs for "id", "name" and "price".

Note: I'm using GSon (https://sites.google.com/site/gson/gson-user-guide) to stringify a set of properties, but I'm not achieving to correctly produce a valid json for that UI.

Code:

        Collection<Atividade> listProducts = storeService.getListPaged(category, rows, page);

        long qty = storeService.getTotal(category);

        List<Properties> lp = new LinkedList<Properties>();

        for (Item i : listProducts) {
            Properties prop = new Properties();

            prop.setProperty("id", Long.toString(i.getId()));
            prop.setProperty("name", i.getName());
            prop.setProperty("price", i.getPrice);
            lp.add(prop);
        }

        Object[][] array = {
            {"total",qty},
            {"rows", lp}
        };

        Gson gson = new GsonBuilder().setDateFormat("dd-MM-yyyy")
                .setPrettyPrinting().create();


        gList = gson.toJson(array);

This code produces the following result, instead of that from above:

[
  [
    "total",
    1
  ],
  [
    "rows",
    [
      {
        "id": "1",
        "name": "Chai",
        "price": "18.00",
      },
    ]
  ]
]

Thanks!

Was it helpful?

Solution

The JSON you are trying to generate

{"total":1,"rows":[{"id":1,"name":"Chai","price":18.00}],"footer":[{"name":"Total","price":18.00}]}

is a JSON object. As such, you can't use an array

Object[][] array = {
        {"total",qty},
        {"rows", lp}
};

to generate it.

Instead, create a POJO class with fields for each JSON name/value pair you want. One for total (which is a number), one for rows (which is an array/list of properties), and one for footer which is some other object).

You can then create an object, initialize its fields, and serialize it with Gson (or other JSON serializer).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top