Thursday, July 8, 2010

How to parse a JSON Object when using multiSearch for jqGrid with Java  


This is a tutorial that shows how to handle a JSON Object that is received in a Struts2Action. This Example is based on the Struts2 Grid Showcase for the Struts2 jQuery Plugin with Grid Extension.

1. First we need to enable the Multi Search Feature for the Grid Component.
< sjg :grid 
Now we can use the multiple search feature like this.
struts2 jquery grid with multiple search
2.) After this we need a String property filter in our Struts2 Action.
private String filters;
public void setFilters(String filters) {
 this.filters = filters;
3.) Now we receive a JSON Object when we use the Search in the Navigator of the Grid.The JSON looks like this example.
4.) To work with this, we need to serialize this as a JSONObject.
JSONObject jsonFilter = (JSONObject) JSONSerializer.toJSON( filters );
5.) Now we can get the value from the JSON Object. First we get the parameter groupOp.
String groupOp = jsonFilter.getString("groupOp");
log.debug("groupOp :" + groupOp);
6.) Now we need the rules as JSONArray and the size of this array.
JSONArray rules = jsonFilter.getJSONArray("rules");
int rulesCount = JSONArray.getDimensions(rules)[0];
log.debug("Count Rules :" + rulesCount);
7.) In a simple for-loop we can get the values of the rule.
for (int i = 0; i < rulesCount; i++) {
 JSONObject rule = rules.getJSONObject(i);
 log.debug("field :" + rule.getString("field"));
 log.debug("op :" + rule.getString("op"));
 log.debug("data :" + rule.getString("data"));
Now you should be able to use this values to build a custom SQL
query or build an hibernate criteria.

What next?

You can also bookmark this post using your favorite bookmarking service:

Related Posts by Categories

Extension Factory Builder