Java – how to pass java beans to jsp page for jqQrid to display using json

javajqgridjson

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.

Best Answer

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!"}
Related Topic