I have a function which is returning Data as List in java class. Now as per my need, I have to convert it into Json Format.
List
Json
Below is my fun
i wrote my own function to return list of object for populate combo box :
public static String getJSONList(java.util.List list,String kelas,String name, String label) { try { Object[] args={}; Class cl = Class.forName(kelas); Method getName = cl.getMethod(name, null); Method getLabel = cl.getMethod(label, null); String json="["; for (int i = 0; i < list.size(); i++) { Object o = list.get(i); if(i>0){ json+=","; } json+="{\"label\":\""+getLabel.invoke(o,args)+"\",\"name\":\""+getName.invoke(o,args)+"\"}"; //System.out.println("Object = " + i+" -> "+o.getNumber()); } json+="]"; return json; } catch (ClassNotFoundException ex) { Logger.getLogger(JSONHelper.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { System.out.println("Error in get JSON List"); ex.printStackTrace(); } return ""; }
and call it from anywhere like :
String toreturn=JSONHelper.getJSONList(list, "com.bean.Contact", "getContactID", "getNumber");