tags:

views:

790

answers:

2

we are trying to use jqGrid with our jsp front end and java back end.

this page is displaying a grid of contacts :

jQuery(document).ready(function(){ 
  jQuery("#list").jqGrid({
    datatype: 'json',
    url:'gridContactDrv.jsp',
    mtype: 'GET',
    height:300,
    width:600,
    colNames:['First Name','Last Name', 'Company', 'Primary Phone','Email'],
    colModel :[ 
      {name:'firstname', index:'firstname', width:100}, 
      {name:'lastname', index:'lastname', width:100 }, 
      {name:'company', index:'company', width:100}, 
      {name:'phone', index:'phone', width:100 }, 
      {name:'email', index:'email', width:200}
    ],
    pager: '#pager',
    rowNum:10,
    rowList:[10,20,30],
    sortname: 'lastname',
    sortorder: 'desc',
    viewrecords: true
  }); 
}); 

gridContactDrv.jsp calls a search function which return a Vector of ContactBeans. In our current (old) way, we loop through the vector, hook out the 5 fields in each bean and contruct a HTML table.

now we want to use json and i can't figure out how to contruct a valid json (obect? array?) to pass to the grid.

    Enumeration e = resultVector.elements();
    while (e.hasMoreElements()) 
    {
     ContactBean c = ContactBean((ContactBean)e.nextElement());
     c.getCompany() 
            c.getFirstName() etc etc and what to do?
        }

btw the ContactBean has many other data members but we are only displaying the 5 fields.

can someone give me some pointers to start? i have searched for a few days and feel like not getting anywhere.

A: 

Have you looked at the JSONWriter class from json.org?

Quoting from the API docs:

 new JSONWriter(myWriter)
     .object()
         .key("JSON")
         .value("Hello, World!")
     .endObject();

which writes

 {"JSON":"Hello, World!"}
Chris Harcourt
A: 

You need to:

  1. Configure your jqGrid instance to expect JSON data
  2. Have something (servlet?) on back-end that would handle JSON request. You could, of course, output grid data as JSON in the same JSP that renders jqGrid but that would largely defeat the purpose (especially for large volumes of data if pagination is involved).
  3. Use JSON library like json-lib to marshall your beans into JSON. I personally like XStream but there are many various implementations available.
ChssPly76