How to convert list data into json in java

前端 未结 7 1210
天涯浪人
天涯浪人 2020-11-30 06:57

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.

Below is my fun

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 07:11

    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");
    

    提交回复
    热议问题