Advertisement
Guest User

JSON

a guest
Dec 13th, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.70 KB | None | 0 0
  1. //class1.isAssignableFrom(class2) est vrai si class 1 est parent de class2
  2.     public static String toJson(Object bean) throws IllegalAccessException {
  3.         String json ="";
  4.         if(bean.getClass()== String.class || bean.getClass() == Date.class){
  5.             return "\""+bean+"\"";
  6.         }
  7.         if(Number.class.isAssignableFrom(bean.getClass())){
  8.             return String.valueOf(bean);
  9.         }
  10.  
  11.         if(Collection.class.isAssignableFrom(bean.getClass()) ){
  12.             json+="[";
  13.             for(Object o:(Collection)bean){
  14.                 json+= ","+toJson(o);
  15.             }
  16.             json = json.replaceFirst(",","");
  17.             json+="]";
  18.             return json;
  19.         }
  20.         if(bean.getClass().isArray()){
  21.             json+="[";
  22.             int length = Array.getLength(bean);
  23.             for (int i = 0; i < length; i ++) {
  24.                 Object arrayElement = Array.get(bean, i);
  25.                 json+= ","+toJson(arrayElement);
  26.             }
  27.  
  28.             json = json.replaceFirst(",","");
  29.             json+="]";
  30.             return json;
  31.         }
  32.         json += "{" ;
  33.         for(Field f:bean.getClass().getDeclaredFields()){
  34.             f.setAccessible(true);
  35.             json+= ",\""+f.getName()+"\":";
  36.             if(f.getType() == String.class || f.getType() == Date.class) {
  37.                 json += "\""+f.get(bean)+"\"";
  38.                 continue;
  39.             }
  40.             if(Object.class.isAssignableFrom(f.getType()) ){
  41.                 json+= toJson(f.get(bean));
  42.                 continue;
  43.             }
  44.  
  45.             json += f.get(bean);
  46.  
  47.  
  48.  
  49.         }
  50.         json = json.replaceFirst(",","");
  51.         json += "}";
  52.  
  53.  
  54.  
  55.        return json;
  56.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement