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 Struts2 Action. 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 
	id="customerstable" 
	...
	navigatorSearch="true"
	navigatorSearchOptions="{multipleSearch:true}"
	...
>
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.
{
	"groupOp":"AND",
	"rules":[
		{
			"field":"customernumber",
			"op":"lt",
			"data":"200"
		}
		,
		{
			"field":"country",
			"op":"eq",
			"data":"USA"
		}
		]
}
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.

25 Kommentare

  1. sepide

    hi :) can you tell me reference of JSONObject???????????
    i cant find it !!!!!!

    Antworten
    1. G Werner

      net.sf.json.JSONObject in json-lib-2.3-jdk15.jar

      Antworten
    2. Lks
  2. cuttle

    My program always aborted without any error message when it run to the following code. All subsequence codes are ignored.

    JSONObject jsonFilter = (JSONObject) JSONSerializer.toJSON( filters );

    Much appreciated if you could kindly help me to solve the problem above.

    Thank you!

    Antworten
    1. jogep (Beitrag Autor)

      can you please post the error codes?
      how does your filter string looks?

      Antworten
  3. cuttle

    Hi jogep, thanks for your reply.

    My error codes are as following:-

    private String filters;

    public void setFilters(String filters) {
    this.filters = filters;
    }

    …………….
    …………….

    public String execute() throws Exception {
    if (this.filters != null) {
    System.out.println(“filters = ” + this.filters);
    jsonFilter = (JSONObject) JSONSerializer.toJSON(this.filters); //<——– (the codes below this line never run.)
    System.out.println("after Json 1");
    groupOp = jsonFilter.getString("groupOp");
    System.out.println("groupOp :" + groupOp);
    rules = jsonFilter.getJSONArray("rules");
    rulesCount = JSONArray.getDimensions(rules)[0];
    System.out.println("rulesCount = " + rulesCount);
    }
    System.out.println("after Json 2");
    return SUCCESS;
    }

    The filter String is: {"groupOp":"AND","rules":[{"field":"remark","op":"bw","data":"test"}]}

    Thank you!

    Antworten
    1. jogep (Beitrag Autor)

      your code looks good, can you please surround this line

      jsonFilter = (JSONObject) JSONSerializer.toJSON(this.filters);

      with an try catch block and post your error message?

      are you sure the json lib is in your deployed classpath?

      Antworten
  4. Trae

    What jars are you using for the JSONObject and JSONSerializer? I was searching around and found a few different jar files.

    Antworten
    1. jogep (Beitrag Autor)

      see the thread for the first comment.

      http://json-lib.sourceforge.net/faq.html#maven2

      Antworten
      1. Trae

        Thank you!

        Antworten
    2. robertogt

      To resolve the problem of cuttle I just add apache libreries

      commons-beanutils.jar;
      commons-collections-3.2.1.jar;
      commons-lang-2.5.jar;
      commons-logging-1.1.1.jar;
      commons-logging-api-1.1.1.jar;
      ezmorph-1.0.6.jar

      Antworten
  5. Pingback: How to parse a JSON Object when using multiSearch for jqGrid with Java

  6. cuttle

    Hi jogep,

    I have tried your suggestion to surround this line jsonFilter = (JSONObject) JSONSerializer.toJSON(this.filters); with an try catch block as below:-

    try {
    jsonFilter = (JSONObject) JSONSerializer.toJSON(filters);
    } catch (JSONException e) {
    e.printStackTrace();
    }

    But the result is same. It still aborted without any error message.

    The json lib is placed in the WEB-INFlib as other jar files.

    Much appreciated if you could kindly help me to solve the problem above.

    Thank you very much!

    Antworten
    1. Nicky

      I had the same problem (Struts2) and eventually to speed up testing created a Java class with Main method. When I ran the code above an error was thrown saying the class ezmorph was missing. I added ezmorph-1.0 to the library and all is working.

      Antworten
  7. jack zhai

    hi.
    How can I get JSON from action in grid.Such as:

    action response the json:
    {“genders”:”MALE:男;FEMALE:女”,”gridModel”:[{“affiliatedOrganization”:{“address”:”广州市白云区长腰岭村”,”email”:”xxx@126.com”,”homePage”:”www.xxx.com”,”id”:1,”name”:”长腰岭一队”,”new”:false,”organizationCategory”:”OWNER”,”tel”:”020-88888888″,”version”:1},”email”:”xxx@126.com”,”gender”:”FEMALE”,”id”:1,”mobile”:”13888888888″,”name”:”李刚”,”new”:false,”qq”:”888888″,”tel”:”020-88888888″,”title”:”经理”,”version”:1}],”loadonce”:false,”organisations”:null,”page”:1,”records”:1,”rows”:15,”searchField”:null,”searchOper”:null,”searchString”:null,”sidx”:””,”sord”:”asc”,”total”:1,”totalrows”:null}

    the jsp:
    <sjg:grid
    id="gridedittable"
    caption="%{getText('organization.list')}"
    dataType="json"
    href="%{remoteurl}"
    gridModel="gridModel"
    …..

    I want to get the "genders"'s value,but I can't!
    Thank you!

    Antworten
  8. steph

    Is there a way to prefill filters on page load ?

    is there any option like :

    navigatorSearchOptions=”{multipleSearch:true, initFilters:%{filters}}”

    Antworten
    1. jogep (Beitrag Autor)

      OGNL should work. You just need a getFilters() method in your grid action.

      Antworten
  9. Mr.Fan

    hi
    rules = jsonFilter.getJSONArray(“rules”);does not work.

    get such message:”net.sf.json.JSONException: JSONObject[“rules”] is not a JSONArray.”

    can you tell me why?

    thanks.

    Antworten
  10. Mr.Fan

    hi
    I change your code,it’s work.

    your code:
    JSONArray rules = jsonFilter.getJSONArray(“rules”);
    int rulesCount = JSONArray.getDimensions(rules)[0];
    log.debug(“Count Rules :” + rulesCount);

    my code:
    Object rules_string =jsonFilter.get(“rules”);
    JSONArray rules = (JSONArray) JSONSerializer.toJSON( rules_string);
    int rulesCount = JSONArray.getDimensions(rules)[0];
    log.debug(“Count Rules :” + rulesCount);

    ok.problem resolved.

    bye.

    Antworten
  11. xiey

    Hi jogep,I have a problem that the property filters is always null in my grid action.But I can’t find zhe problem.

    private String filters;
    public void setFilters(String filters) {
    this.filters = filters;
    }

    Antworten
  12. Xiey

    I use IE 7. And the the parameter “filters” always null.What’s the ploblem?

    Antworten
  13. Prafull Pohekar

    Yes It is Working My Problem is Sloved

    Antworten
  14. sri

    Hi,

    I am using struts2 jquery grid in my application.

    My problem is
    i want to populate grid columns dynamically?
    So

    How to read json string values in struts2 jsp page.

    My jsonString like this:

    {“al”:[“id”,”data”,”disc”],”data”:null,”disc”:null,”grid”:[{“data”:”data1″,”disc”:”one”,”id”:”1″},{“data”:”data2″,”disc”:”two”,”id”:”2″},{“data”:”data3″,”disc”:”three”,”id”:”3″}],”gridmodel”:[{“data”:”data1″,”disc”:”one”,”id”:”1″},{“data”:”data2″,”disc”:”two”,”id”:”2″},{“data”:”data3″,”disc”:”three”,”id”:”3″}],”id”:null}

    i want “al” in my jsp

    For that i write code in my jsp…

    jsp
    ————-

    How to access “al” in strust2 jsp

    Thank you

    Antworten
  15. Hà Văn Đao

    Thank very much for your tutorial! It is helpful to you to solve problem in my project !!!

    Antworten
  16. Daniela

    Dear Jogep,
    thank you so much for this helpfull code.
    Unfortunately I have the same issue of Xiey, i.e. i always retrieve NULL filters in my action.

    This is my grid

    and in the action

    private String filters;

    public String getFilters() {
    return filters;
    }
    public void setFilters(String filters) {
    this.filters = filters;
    }

    ….

    public String execute()
    {
    }
    if (this.filters!=null){
    System.out.println(“JSON filters NOT NULL: ” + this.filters);
    JSONObject jsonFilter = (JSONObject) JSONSerializer.toJSON( this.filters );
    ….}else
    System.out.println(“JSON filters NULL: ” );

    Could you kindly support me?
    Is there something I miss?

    Thanks in advance and best regards

    Antworten

Kommentar verfassen