JSon-Methods


<%@ page import = "java.util.* " %>
<%@ page import = "java.lang.reflect.* " %>

<%!

  private String getJSonArray(Object[] objs) {
     StringBuilder sb = new StringBuilder();
     if (objs.length==0) {
      return "[]";
     }
     sb.append("[ " );
     int n = objs.length;       
     for(int i=0; i<n; i++) {
       sb.append(getJSon(objs[i]));
       if (i<n-1) {
          sb.append(", ");
       }
     }
     sb.append(" ]");
     return sb.toString();
  }


  private String getJSonArraylist(ArrayList objs) {
     StringBuilder sb = new StringBuilder();
     if (objs.size()==0) {
      return "[]";
     }
     sb.append("[ " );
     int n = objs.size();       
     for(int i=0; i<n; i++) {
       sb.append(getJSon(objs.get(i)));
       if (i<n-1) {
          sb.append(", ");
       }
     }
     sb.append(" ]");
     return sb.toString();
  }


  private String getJSon(Object obj) {
     StringBuilder sb = new StringBuilder();
     try {     
       Class c = obj.getClass();
       Field[] fields; 
       fields = c.getDeclaredFields();
        // {  {"name": "Meier59", "mnr":12345} 
       sb.append("{");
       int n=fields.length-1;
       for(int i=0; i<n; i++) {
         Field field = fields[i];
         sb.append("\"");
         sb.append(field.getName());
         sb.append("\": ");
         String s=field.getType().toString();
         if (s.indexOf("String")>0) {
            sb.append("\"");
            sb.append(field.get(obj));
            sb.append("\"");
         }
         else {
          sb.append(field.get(obj));
         }
         if (i<n-1) {
            sb.append(", ");
         }
       }
       sb.append("}");
       }
     catch ( IllegalAccessException e) {
     }
     return sb.toString();
  }
 
%>



<%@ 
  page import = "java.text.* " 
%>


<%

  ArrayList<Employee> liste= new ArrayList<Employee>();
  liste.add( new Employee("Smith",12345));
  liste.add( new Employee("Miller",12365));
  liste.add( new Employee("Brandt",12445));
  liste.add( new Employee("Schmitt",14345));
    // now get the JSon-String
  String ergebnis = getJSonArraylist(liste);
  out.println(ergebnis);
%>






Druckbare Version


2. JSP Sample