Advertisement
Guest User

MyJSONParser.java

a guest
Sep 6th, 2012
586
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.android4;
  2.  
  3. import java.lang.reflect.Array;
  4. import java.lang.reflect.Field;
  5. import java.lang.reflect.Modifier;
  6.  
  7. import org.json.JSONArray;
  8. import org.json.JSONException;
  9. import org.json.JSONObject;
  10.  
  11. /**
  12.  * Parses any class to JSON and populates any class from JSON using Android native JSON, without any third-party libraries.
  13.  *
  14.  * @author Ender Muab'Dib
  15.  *
  16.  */
  17. public class MyJSONParser {
  18.     private static int privacy = 2;
  19.  
  20.     /**
  21.      * p = 0 --> Only for public fields
  22.      * p = 1 --> Only for public + protected fields
  23.      * p = 2 --> All fields: public + protected + private. Use only under your own responsability.
  24.      */
  25.     public static void setPrivacyLevel(int p) {
  26.     if ((p >= 0) && (p <= 2)) {
  27.         privacy = p;
  28.     }
  29.     }
  30.  
  31.     /**
  32.      * privacy = 0 --> Only for public fields
  33.      * privacy = 1 --> Only for public + protected fields
  34.      * privacy = 2 --> All fields: public + protected + private. Use only under your own responsability.
  35.      */
  36.     public static int getPrivacyLevel() {
  37.     return privacy;
  38.     }
  39.  
  40.     /**
  41.      * @return an object of type classname with its PUBLIC fields full with the js info
  42.      */
  43.     public static Object populateObjectFromJSON(Class<?> classname, JSONObject js) {
  44.     Object obj = null;
  45.     System.out.println("Populating " + classname.getSimpleName() + " -with- " + js.toString());
  46.     try {
  47.         obj = classname.newInstance();
  48.     } catch (InstantiationException e1) {
  49.         System.err.println(e1.getMessage());
  50.         return null;
  51.     } catch (IllegalAccessException e1) {
  52.         System.err.println(e1.getMessage());
  53.         return null;
  54.     }
  55.  
  56.     Field[] fields;
  57.  
  58.     if (privacy == 0) {
  59.         fields = classname.getFields();
  60.     } else {
  61.         fields = classname.getDeclaredFields();
  62.     }
  63.  
  64.     for (Field f : fields) {
  65.         // System.out.println("Declared " + f.getName());
  66.  
  67.         if ((privacy == 2) && (Modifier.isPrivate(f.getModifiers()))) {
  68.         f.setAccessible(true);
  69.         }
  70.  
  71.         try {
  72.         if (js.has(f.getName())) {
  73.             String type = f.getType().getSimpleName();
  74.             if (type.equalsIgnoreCase("boolean")) {
  75.             f.setBoolean(obj, js.getBoolean(f.getName()));
  76.             } else if (type.equalsIgnoreCase("int")) {
  77.             f.setInt(obj, js.getInt(f.getName()));
  78.             } else if (type.equalsIgnoreCase("double")) {
  79.             f.setDouble(obj, js.getDouble(f.getName()));
  80.             } else if (type.equalsIgnoreCase("float")) {
  81.             f.setFloat(obj, (float) js.getDouble(f.getName()));
  82.             } else if (type.equalsIgnoreCase("string")) {
  83.             f.set(obj, js.getString(f.getName()));
  84.             } else if (f.getType().isArray()) {
  85.             f.set(obj, Array.newInstance(f.getType().getComponentType(), js.getJSONArray(f.getName()).length()));
  86.             insertArrayFromJSON(f.get(obj), js.getJSONArray(f.getName()));
  87.             } else {
  88.             f.set(obj, populateObjectFromJSON(f.getType(), js.getJSONObject(f.getName())));
  89.             }
  90.         }
  91.         } catch (IllegalArgumentException e) {
  92.         System.err.println(e.getMessage());
  93.         } catch (IllegalAccessException e) {
  94.         System.err.println(e.getMessage());
  95.         } catch (JSONException e) {
  96.         System.err.println(e.getMessage());
  97.         }
  98.  
  99.         if ((privacy == 2) && (Modifier.isPrivate(f.getModifiers()))) {
  100.         f.setAccessible(false);
  101.         }
  102.     }
  103.  
  104.     return obj;
  105.     }
  106.  
  107.     /**
  108.      * @param o
  109.      *            This object will be fill up with the JSONArray js data
  110.      */
  111.     public static void insertArrayFromJSON(Object o, JSONArray js) throws IllegalArgumentException, NegativeArraySizeException, IllegalAccessException, JSONException {
  112.     Class<?> c = o.getClass();
  113.  
  114.     String type = c.getComponentType().getSimpleName();
  115.  
  116.     for (int i = 0; i < js.length(); i++) {
  117.         if (c.getComponentType().isArray()) {
  118.         Array.set(o, i, Array.newInstance(c.getComponentType().getComponentType(), js.getJSONArray(i).length()));
  119.         insertArrayFromJSON(Array.get(o, i), js.getJSONArray(i));
  120.         } else if (!c.getComponentType().isPrimitive() && (!type.equalsIgnoreCase("string"))) {
  121.         Array.set(o, i, populateObjectFromJSON(c.getComponentType(), js.getJSONObject(i)));
  122.         } else {
  123.         Array.set(o, i, js.get(i));
  124.         }
  125.     }
  126.     }
  127.  
  128.     /**
  129.      * @param obj Object to convert in JSON format
  130.      * @return JSONOBject with all obj initialited AND PUBLIC fields.
  131.      */
  132.     public static JSONObject parseObjectToJSONClass(Object obj) {
  133.     JSONObject js = new JSONObject();
  134.  
  135.     Class<?> c = obj.getClass();
  136.  
  137.     Field[] fields;
  138.  
  139.     if (privacy == 0) {
  140.         fields = c.getFields();
  141.     } else {
  142.         fields = c.getDeclaredFields();
  143.     }
  144.  
  145.     for (Field f : fields) {
  146.         if ((privacy == 2) && (Modifier.isPrivate(f.getModifiers()))) {
  147.         f.setAccessible(true);
  148.         }
  149.  
  150.         try {
  151.         System.out.println(f.getName() + " - " + f.getType().getSimpleName() + " - " + f.get(obj));
  152.  
  153.         String name = f.getName();
  154.         String type = f.getType().getSimpleName();
  155.         if (f.get(obj) != null) {
  156.             if (type.equalsIgnoreCase("boolean")) {
  157.             js.put(name, f.getBoolean(obj));
  158.             } else if (type.equalsIgnoreCase("int")) {
  159.             js.put(name, f.getInt(obj));
  160.             } else if (type.equalsIgnoreCase("double")) {
  161.             js.put(name, f.getDouble(obj));
  162.             } else if (type.equalsIgnoreCase("float")) {
  163.             js.put(name, f.getFloat(obj));
  164.             } else if (type.equalsIgnoreCase("string")) {
  165.             js.put(name, (String) f.get(obj));
  166.             } else if (type.endsWith("]")) {
  167.             js.put(name, generateJSONArray(f.get(obj)));
  168.             } else {
  169.             js.put(name, parseObjectToJSONClass(f.get(obj)));
  170.             }
  171.         }
  172.         } catch (IllegalArgumentException e) {
  173.         System.err.println(e.getMessage());
  174.         } catch (IllegalAccessException e) {
  175.         System.err.println(e.getMessage());
  176.         } catch (JSONException e) {
  177.         System.err.println(e.getMessage());
  178.         }
  179.    
  180.         if ((privacy == 2) && (Modifier.isPrivate(f.getModifiers()))) {
  181.         f.setAccessible(false);
  182.         }
  183.     }
  184.    
  185.     return js;
  186.     }
  187.  
  188.     /**
  189.      *
  190.      * @param o  Array object to convert in JSONArray format
  191.      * @return a JSONArray with all the o components.
  192.      */
  193.     public static JSONArray generateJSONArray(Object o) throws ArrayIndexOutOfBoundsException, IllegalArgumentException, JSONException {
  194.     JSONArray ar = new JSONArray();
  195.     for (int i = 0; i < Array.getLength(o); i++) {
  196.         if (Array.get(o, i).getClass().isArray()) {
  197.         ar.put(i, generateJSONArray(Array.get(o, i)));
  198.         } else {
  199.         ar.put(i, Array.get(o, i));
  200.         }
  201.     }
  202.     return ar;
  203.     }
  204. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement