jqGrid JSON Java Model
I've been using the JQuery plugin jqGrid for several months now. I've been really pleased with it. Up to this point, due to laziness, I've been building my JSON string manually using StringBuilder. Tonight I decided it was time to make this easier.
jqGrid accepts different forms of data to represent the grid. I prefer to use JSON because its very light weight and transforming Java objects to JSON is a light weight task. Here is an example of a JSON string used by jqGrid. It is very simple. It only contains two columns of data and a handful of rows.
{"page":"1","records":5,"rows": [
{"cell":["Blue","This is blue"],"id":1},
{"cell":["Green","This is green"],"id":2},
{"cell":["Re","This is red"],"id":3},
{"cell":["Black","This is Black"],"id":4},
{"cell":["Purple","This is purple"],"id":5}
],"total":"1"}
To model this string in java I had to create two objects. JQGridJSONModel.java and JQGridRow.java. See the code below.
public class JQGridJSONModel {
private String page;
private String total;
private Integer records;
private List<JQGridRow> rows;
// getters and setters omitted
}
public class JQGridRow {
private Integer id;
private List<String> cell;
// getters and setters omitted
}
Using these classes is quite simple. To generate the JSON string above I have a Color class that contains an id, name, and description. Once I retrieve the list from the database I do the following.
JQGridJSONModel json = new JQGridJSONModel();
json.setPage("1");
json.setRecords(colors.size());
json.setTotal("1");
List<JQGridRow> rows = new ArrayList<JQGridRow>();
for (Color c : colors) {
JQGridRow row = new JQGridRow();
row.setId(c.getId());
List<String> cells = new ArrayList<String>();
cells.add(c.getName());
cells.add(c.getDescription());
row.setCell(cells);
rows.add(row);
}
json.setRows(rows);
Then just use your favorite JSON serializer to generate your JSON string. Just make sure you are able to exclude the class parameter that generally gets thrown into the serialization process. I really like FlexJSON.
JSONSerializer serializer = new JSONSerializer();
String jsonResult = serializer.exclude("*.class").deepSerialize(json);
That's it. Feel free to do with this as you wish