android解析json

来源:互联网 发布:电脑自带编程软件在哪 编辑:程序博客网 时间:2024/06/05 03:01

 最近客户端需求变更,服务器发送json格式的数据解析,但是我在做javaEE的时候,发现json是可以直接得到List  ,class对象这些的,而在本身的android里面,省略了这些,所以这些需要自己来写,个人觉得,如果封装一个工具类就好了,如果使用反射机制就可以封装出来一个,但是实体类的字段就必须是public的!
      下面是这个工具类的代码:

   

[java] view plaincopy
  1. <p>package com.zhangkeinfo.json.util;</p><p>  
  2. import java.lang.reflect.Field;  
  3. import java.lang.reflect.Type;  
  4. import java.util.ArrayList;  
  5. import java.util.List;</p><p>import org.json.JSONArray;  
  6. import org.json.JSONException;  
  7. import org.json.JSONObject;</p><p>import android.util.Log;  
  8. /** 
  9.  * json util class ,use in for analyzing json  
  10.  * @author spring sky 
  11.  * Email:vipa1888@163.com 
  12.  * QQ:840950105 
  13.  * 2011-12-14 15:39:51 
  14.  * 
  15.  */  
  16. public class JsonUtil {  
  17.  private static final String TAG = "jsonUtil";  
  18.  private JSONObject jsonObject;  
  19.  private JsonUtil(String json)  
  20.  {  
  21.   Log.e(TAG, "json="+json);  
  22.   jsonObject = getJsonObject(json);  
  23.   if(jsonObject==null)  
  24.   {  
  25.    Log.e(TAG, "jsonobject is null");  
  26.   }  
  27.  }  
  28.    
  29.  private JsonUtil() {  
  30.   super();  
  31.  }</p><p> public static JsonUtil newJsonUtil(String json)  
  32.  {  
  33.   JsonUtil util =  new JsonUtil(json);  
  34.   return util;  
  35.  }  
  36.  /** 
  37.   * get json object  
  38.   * @param json  json data 
  39.   * @return  JOSNObject 
  40.   */  
  41.  public JSONObject getJsonObject(String json)   
  42.  {  
  43.   JSONObject jsonObject = null;  
  44.   try {  
  45.    jsonObject = new JSONObject(json);  
  46.   } catch (JSONException e) {  
  47.    Log.e(TAG, "create jsonobject exception");  
  48.    e.printStackTrace();  
  49.   }  
  50.   return jsonObject;  
  51.  }  
  52.  /** 
  53.   * get String data 
  54.   * @param json  json data 
  55.   * @param key param 
  56.   * @return  String data 
  57.   * @throws JSONException 
  58.   */  
  59.  public  String getString(String key)  
  60.  {  
  61.   if(jsonObject!= null)  
  62.   {  
  63.    try {  
  64.     return jsonObject.getString(key);  
  65.    } catch (Exception e) {  
  66.     e.printStackTrace();  
  67.     return null;  
  68.    }  
  69.   }else{  
  70.    return null;  
  71.   }  
  72.     
  73.  }  
  74.  /** 
  75.   * get String data 
  76.   * @param json  json data 
  77.   * @param key param 
  78.   * @return  int data 
  79.   * @throws JSONException 
  80.   */  
  81.  public  int getInt(String key)   
  82.  {  
  83.   if(jsonObject!= null)  
  84.   {  
  85.    try {  
  86.     return jsonObject.getInt(key);  
  87.    } catch (Exception e) {  
  88.     e.printStackTrace();  
  89.     return -1;  
  90.    }  
  91.   }else{  
  92.    return -1;  
  93.   }  
  94.     
  95.  }  
  96.  /** 
  97.   * get Double data 
  98.   * @param json  json data 
  99.   * @param key param 
  100.   * @return  double data 
  101.   * @throws JSONException 
  102.   */  
  103.  public  double getDouble(String key)  
  104.  {  
  105.   if(jsonObject!= null)  
  106.   {  
  107.    try {  
  108.     return jsonObject.getDouble(key);  
  109.    } catch (Exception e) {  
  110.     e.printStackTrace();  
  111.     return -1;  
  112.    }  
  113.   }else{  
  114.    return -1;  
  115.   }  
  116.     
  117.  }  
  118.  /** 
  119.   * This Method use in jsonObject get current class with object  
  120.   * @param jsonObject 
  121.   * @param c  class  
  122.   * @return  object  
  123.   * @throws Exception 
  124.   */  
  125.  public  Object getObject(Class<?> c)  
  126.  {  
  127.   if(jsonObject!=null)  
  128.   {  
  129.    try {  
  130.     return getObject(c.getSimpleName().toLowerCase(),c);  
  131.    } catch (Exception e) {  
  132.     e.printStackTrace();  
  133.     return null;  
  134.    }  
  135.   }else{  
  136.    return null;  
  137.   }  
  138.  }  
  139.  /** 
  140.   * This Method use in jsonObject get current class with object  
  141.   * @param jsonObject 
  142.   * @param key   query key  
  143.   * @param c  class  
  144.   * @return  object  
  145.   * @throws Exception 
  146.   */  
  147.  public  Object getObject(String key,Class<?> c)  
  148.  {  
  149.   if(jsonObject!=null)  
  150.   {  
  151.    try {  
  152.     return getObject(jsonObject, key, c);  
  153.    } catch (Exception e) {  
  154.     e.printStackTrace();  
  155.     return null;  
  156.    }  
  157.   }else{  
  158.    return null;  
  159.   }  
  160.  }  
  161.  public Object getObject(JSONObject jsonObject,Class<?> c)  
  162.  {  
  163.   try {  
  164.    return getObject(jsonObject, c.getSimpleName().toLowerCase(), c);  
  165.   } catch (Exception e) {  
  166.    e.printStackTrace();  
  167.    return null;  
  168.   }  
  169.  }  
  170.  /** 
  171.   * This Method use in jsonObject get current class with object  
  172.   * @param jsonObject 
  173.   * @param key   query key  
  174.   * @param c  class  
  175.   * @return  object  
  176.   * @throws InstantiationException  
  177.   * @throws IllegalAccessException  
  178.   * @throws Exception 
  179.   */  
  180.  public  Object getObject(JSONObject jsonObject, String key,Class<?> c) throws IllegalAccessException, InstantiationException   
  181.  {  
  182.   Log.e(TAG,"key ==  " + key);  
  183.   Object bean =null ;  
  184.     
  185.   if(jsonObject!=null)  
  186.   {  
  187.    JSONObject jo = null;  
  188.    if(key!=null)  
  189.    {  
  190.      try {  
  191.      jo =  jsonObject.getJSONObject(key);  
  192.     } catch (JSONException e) {  
  193.      e.printStackTrace();  
  194.      jo = null;  
  195.     }  
  196.    }else{  
  197.     jo = jsonObject;  
  198.    }  
  199.    if(jo!=null)  
  200.    {  
  201.     if(c.equals(null))  
  202.     {  
  203.      Log.e(TAG, "class is null");  
  204.      try {  
  205.       bean = jo.get(key);  
  206.      } catch (JSONException e) {  
  207.       e.printStackTrace();  
  208.       bean = null;  
  209.      }  
  210.     }else{  
  211.      bean = c.newInstance();  
  212.      Field[] fs = c.getDeclaredFields();  
  213.      for (int i = 0; i < fs.length; i++) {  
  214.       Field f = fs[i];  
  215.       f.setAccessible(true);  
  216.       Type type = f.getGenericType();  
  217.       String value;  
  218.       try {  
  219.        value = jo.getString(f.getName());  
  220.       } catch (Exception e) {  
  221.        value =null;  
  222.       }  
  223.       Log.e(TAG,f.getName()+"="+value);  
  224.       if(type.equals(int.class))  
  225.       {  
  226.        f.setInt(bean,value==null?-1:Integer.valueOf(value));  
  227.       }else if(type.equals(double.class)){  
  228.        f.setDouble(bean,value==null?-1:Double.valueOf(value));  
  229.       }else if(type.getClass().equals(java.util.List.class)){  
  230.          
  231.        Log.e(TAG, "this type is list");  
  232.       }else{  
  233.        f.set(bean,value);  
  234.       }  
  235.      }  
  236.     }  
  237.    }else{  
  238.     Log.e(TAG, "in jsonobject not key ");  
  239.    }  
  240.   }else{  
  241.    Log.e(TAG, "current param jsonobject is null");  
  242.   }  
  243.   return bean;  
  244.  }  
  245.  /** 
  246.   * This method use in jsonObject get list object 
  247.   * @param key  list key 
  248.   * @param objectKey  object key 
  249.   * @param c  object 
  250.   * @return   list 
  251.   * @throws Exception 
  252.   */  
  253.  public List<Object> getList(String key ,Class<?> c,int total)  
  254.  {  
  255.   List<Object> list = null;  
  256.   try {  
  257.    if(jsonObject!=null)  
  258.    {  
  259.     list = new ArrayList<Object>();  
  260.     if(total==1)  
  261.     {  
  262.      Object object = getObject(key, c);  
  263.      list.add(object);  
  264.     }else{  
  265.      JSONArray jsonArray = jsonObject.getJSONArray(key);  
  266.      if(!jsonArray.isNull(0))  
  267.      {  
  268.       for (int i = 0; i < jsonArray.length(); i++) {  
  269.        JSONObject jsObject = jsonArray.getJSONObject(i);  
  270.        Object object = getObject(jsObject, null, c);  
  271.        if(object!=null)  
  272.        {  
  273.         list.add(object);  
  274.        }  
  275.       }  
  276.      }  
  277.     }  
  278.       
  279.    }  
  280.   } catch (Exception e) {  
  281.    e.printStackTrace();  
  282.    list=null;  
  283.   }   
  284.   return list;  
  285.  }  
  286.  /** 
  287.   * Test class field value   
  288.   * @param c   
  289.   * @param classObject 
  290.   * @throws IllegalArgumentException 
  291.   * @throws IllegalAccessException 
  292.   */  
  293.  public static String getFieldValue(Class<?> c,Object classObject) throws IllegalArgumentException, IllegalAccessException  
  294.  {  
  295.   StringBuffer sb = new StringBuffer();  
  296.   Field[] fs = c.getFields();  
  297.   for (int i = 0; i < fs.length; i++) {  
  298.    String s = fs[i].getName()+"="+fs[i].get(classObject);  
  299.    sb.append(s).append("\n");  
  300.   }  
  301. //  Log.e(TAG, sb.toString());  
  302.   return sb.toString();  
  303.  }  
  304. }  
  305. </p>  
  306.    

一个测试的实体类:

wallpaper :

[html] view plaincopy
  1. package com.zhangkeinfo.json.model.response;  
  2.   
  3.   
  4.   
  5. public class Wallpaper{  
  6.     public int id;  
  7.     public String name;  
  8.     public int rank;  
  9.     public String img;  
  10.     public String preview1url;  
  11.     public String preview2url;  
  12.     public String preview3url;  
  13.     public String msg;  
  14.     public int ptotal;  
  15. }  

 

Price:

[html] view plaincopy
  1. package com.zhangkeinfo.json.model.response;  
  2.   
  3. public class Price {  
  4.     public int id;  
  5.     public int price ;  
  6.     public String name;  
  7. }  


解析测试:

[java] view plaincopy
  1. package com.zhangkeinfo.json;  
  2.   
  3.   
  4. import java.lang.reflect.Field;  
  5. import java.util.HashMap;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8.   
  9.   
  10. import com.zhangkeinfo.json.model.request.ZmxURL;  
  11. import com.zhangkeinfo.json.model.response.Price;  
  12. import com.zhangkeinfo.json.model.response.Wallpaper;  
  13. import com.zhangkeinfo.json.network.NetWorkUtil;  
  14. import com.zhangkeinfo.json.util.JsonUtil;  
  15.   
  16. import android.app.Activity;  
  17. import android.os.Bundle;  
  18. import android.view.View;  
  19. import android.view.View.OnClickListener;  
  20. import android.widget.Button;  
  21. import android.widget.TextView;  
  22.   
  23. public class MainActivity1 extends Activity implements OnClickListener{  
  24.     private static final String TAG = "MainActivity";  
  25.     Button button1,button2;  
  26.     TextView text;  
  27.     /** 
  28.      * 测试的json数据 
  29.      */  
  30.     public String json = "{\"id\":\"17\",\"res\":\"1\",\"wallpaper\":{\"id\":\"50\",\"name\":\"壁纸1\",\"rank\":\"0\",\"img\":\"img/a.png\",\"preview1url\":\"img/a.png\",\"preview2url\":\"img/a.png\",\"preview3url\":\"img/a.png\",\"msg\":\"\",\"ptotal\":\"1\"},\"price\":[{\"id\":\"1\",\"price\":\"1\",\"name\":\"点播\"},{\"id\":\"2\",\"price\":\"6\",\"name\":\"包月\"}]}";  
  31.     @Override  
  32.     public void onCreate(Bundle savedInstanceState) {  
  33.         super.onCreate(savedInstanceState);  
  34.         setContentView(R.layout.main);  
  35.           
  36.         button1 = (Button) this.findViewById(R.id.button1);  
  37.         button1.setOnClickListener(this);  
  38.           
  39.     }  
  40.     @Override  
  41.     public void onClick(View v) {  
  42.         switch (v.getId()) {  
  43.         case R.id.button1:  
  44.             try {  
  45.                 StringBuffer sb = new StringBuffer();  
  46.                 /** 
  47.                  * 得到实例对象 
  48.                  */  
  49.                 JsonUtil util1 = JsonUtil.newJsonUtil(json);  
  50.                 /* 
  51.                  * 得到list对象 第三个参数是这个list中一共有多少个对象  //ptotal就是获取订阅方式的个数 
  52.                  */  
  53.                 List<Object> list = util1.getList("prices", Price.class,util1.get("ptotal"));                     for(int i =0 ;i< list.size();i++)  
  54.                 {  
  55.                     Price price = (Price) list.get(i);  
  56.                     sb.append(JsonUtil.getFieldValue(Price.class, price));  
  57.                 }  
  58.                 /** 
  59.                  * 得到对象 
  60.                  */  
  61.                 Wallpaper wallpaper =  (Wallpaper) util1.getObject( Wallpaper.class);  
  62.                 if(wallpaper!=null)  
  63.                 {  
  64.                     /** 
  65.                      * 反射得到字段的内容 
  66.                      */  
  67.                     Field[] fs = Wallpaper.class.getFields();  
  68.                     for (int i = 0; i < fs.length; i++) {  
  69.                         String s = fs[i].getName()+"="+fs[i].get(wallpaper);  
  70.                         sb.append(s).append("\n");  
  71.                     }  
  72.                 }else{  
  73.                     sb.append("wallpaper is null");  
  74.                 }  
  75.                 text.setText(sb.toString());  
  76.                   
  77.             } catch (Exception e) {  
  78.                 e.printStackTrace();  
  79.             }  
  80.             break;  
  81.         }  
  82.           
  83.     }  
  84. }  


 

上面的代码,复制测试就可以了,本人也只是对反射机制了解一个基础,更深层次的还需要深入的研究的!



(源自:http://blog.csdn.net/vipa1888/article/details/7071389)