android解析json

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

   

package com.zhangkeinfo.json.util;

import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List;

import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;

import android.util.Log; /**  * json util class ,use in for analyzing json  * @author spring sky  * Email:vipa1888@163.com  * QQ:840950105  * 2011-12-14 15:39:51  *  */ public class JsonUtil {  private static final String TAG = "jsonUtil";  private JSONObject jsonObject;  private JsonUtil(String json)  {   Log.e(TAG, "json="+json);   jsonObject = getJsonObject(json);   if(jsonObject==null)   {    Log.e(TAG, "jsonobject is null");   }  }    private JsonUtil() {   super();  }

 public static JsonUtil newJsonUtil(String json)  {   JsonUtil util =  new JsonUtil(json);   return util;  }  /**   * get json object   * @param json  json data   * @return  JOSNObject   */  public JSONObject getJsonObject(String json)  {   JSONObject jsonObject = null;   try {    jsonObject = new JSONObject(json);   } catch (JSONException e) {    Log.e(TAG, "create jsonobject exception");    e.printStackTrace();   }   return jsonObject;  }  /**   * get String data   * @param json  json data   * @param key param   * @return  String data   * @throws JSONException   */  public  String getString(String key)  {   if(jsonObject!= null)   {    try {     return jsonObject.getString(key);    } catch (Exception e) {     e.printStackTrace();     return null;    }   }else{    return null;   }     }  /**   * get String data   * @param json  json data   * @param key param   * @return  int data   * @throws JSONException   */  public  int getInt(String key)  {   if(jsonObject!= null)   {    try {     return jsonObject.getInt(key);    } catch (Exception e) {     e.printStackTrace();     return -1;    }   }else{    return -1;   }     }  /**   * get Double data   * @param json  json data   * @param key param   * @return  double data   * @throws JSONException   */  public  double getDouble(String key)  {   if(jsonObject!= null)   {    try {     return jsonObject.getDouble(key);    } catch (Exception e) {     e.printStackTrace();     return -1;    }   }else{    return -1;   }     }  /**   * This Method use in jsonObject get current class with object   * @param jsonObject   * @param c  class   * @return  object   * @throws Exception   */  public  Object getObject(Class<?> c)  {   if(jsonObject!=null)   {    try {     return getObject(c.getSimpleName().toLowerCase(),c);    } catch (Exception e) {     e.printStackTrace();     return null;    }   }else{    return null;   }  }  /**   * This Method use in jsonObject get current class with object   * @param jsonObject   * @param key   query key   * @param c  class   * @return  object   * @throws Exception   */  public  Object getObject(String key,Class<?> c)  {   if(jsonObject!=null)   {    try {     return getObject(jsonObject, key, c);    } catch (Exception e) {     e.printStackTrace();     return null;    }   }else{    return null;   }  }  public Object getObject(JSONObject jsonObject,Class<?> c)  {   try {    return getObject(jsonObject, c.getSimpleName().toLowerCase(), c);   } catch (Exception e) {    e.printStackTrace();    return null;   }  }  /**   * This Method use in jsonObject get current class with object   * @param jsonObject   * @param key   query key   * @param c  class   * @return  object   * @throws InstantiationException   * @throws IllegalAccessException   * @throws Exception   */  public  Object getObject(JSONObject jsonObject, String key,Class<?> c) throws IllegalAccessException, InstantiationException  {   Log.e(TAG,"key ==  " + key);   Object bean =null ;      if(jsonObject!=null)   {    JSONObject jo = null;    if(key!=null)    {      try {      jo =  jsonObject.getJSONObject(key);     } catch (JSONException e) {      e.printStackTrace();      jo = null;     }    }else{     jo = jsonObject;    }    if(jo!=null)    {     if(c.equals(null))     {      Log.e(TAG, "class is null");      try {       bean = jo.get(key);      } catch (JSONException e) {       e.printStackTrace();       bean = null;      }     }else{      bean = c.newInstance();      Field[] fs = c.getDeclaredFields();      for (int i = 0; i < fs.length; i++) {       Field f = fs[i];       f.setAccessible(true);       Type type = f.getGenericType();       String value;       try {        value = jo.getString(f.getName());       } catch (Exception e) {        value =null;       }       Log.e(TAG,f.getName()+"="+value);       if(type.equals(int.class))       {        f.setInt(bean,value==null?-1:Integer.valueOf(value));       }else if(type.equals(double.class)){        f.setDouble(bean,value==null?-1:Double.valueOf(value));       }else if(type.getClass().equals(java.util.List.class)){                Log.e(TAG, "this type is list");       }else{        f.set(bean,value);       }      }     }    }else{     Log.e(TAG, "in jsonobject not key ");    }   }else{    Log.e(TAG, "current param jsonobject is null");   }   return bean;  }  /**   * This method use in jsonObject get list object   * @param key  list key   * @param objectKey  object key   * @param c  object   * @return   list   * @throws Exception   */  public List<Object> getList(String key ,Class<?> c,int total)  {   List<Object> list = null;   try {    if(jsonObject!=null)    {     list = new ArrayList<Object>();     if(total==1)     {      Object object = getObject(key, c);      list.add(object);     }else{      JSONArray jsonArray = jsonObject.getJSONArray(key);      if(!jsonArray.isNull(0))      {       for (int i = 0; i < jsonArray.length(); i++) {        JSONObject jsObject = jsonArray.getJSONObject(i);        Object object = getObject(jsObject, null, c);        if(object!=null)        {         list.add(object);        }       }      }     }         }   } catch (Exception e) {    e.printStackTrace();    list=null;   }   return list;  }  /**   * Test class field value    * @param c    * @param classObject   * @throws IllegalArgumentException   * @throws IllegalAccessException   */  public static String getFieldValue(Class<?> c,Object classObject) throws IllegalArgumentException, IllegalAccessException  {   StringBuffer sb = new StringBuffer();   Field[] fs = c.getFields();   for (int i = 0; i < fs.length; i++) {    String s = fs[i].getName()+"="+fs[i].get(classObject);    sb.append(s).append("\n");   } //  Log.e(TAG, sb.toString());   return sb.toString();  } }

 

一个测试的实体类:

wallpaper :

package com.zhangkeinfo.json.model.response;



public class Wallpaper{
	public int id;
	public String name;
	public int rank;
	public String img;
	public String preview1url;
	public String preview2url;
	public String preview3url;
	public String msg;
	public int ptotal;
}

Price:

package com.zhangkeinfo.json.model.response;

public class Price {
	public int id;
	public int price ;
	public String name;
}


解析测试:

package com.zhangkeinfo.json;


import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.zhangkeinfo.json.model.request.ZmxURL;
import com.zhangkeinfo.json.model.response.Price;
import com.zhangkeinfo.json.model.response.Wallpaper;
import com.zhangkeinfo.json.network.NetWorkUtil;
import com.zhangkeinfo.json.util.JsonUtil;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity1 extends Activity implements OnClickListener{
	private static final String TAG = "MainActivity";
	Button button1,button2;
	TextView text;
	/**
	 * 测试的json数据
	 */
	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\":\"包月\"}]}";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        button1 = (Button) this.findViewById(R.id.button1);
        button1.setOnClickListener(this);
        
    }
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button1:
			try {
				StringBuffer sb = new StringBuffer();
				/**
				 * 得到实例对象
				 */
				JsonUtil util1 = JsonUtil.newJsonUtil(json);
				/*
				 * 得到list对象 第三个参数是这个list中一共有多少个对象  //ptotal就是获取订阅方式的个数
				 */
				List<Object> list = util1.getList("prices", Price.class,util1.get("ptotal"));						for(int i =0 ;i< list.size();i++)
				{
					Price price = (Price) list.get(i);
					sb.append(JsonUtil.getFieldValue(Price.class, price));
				}
				/**
				 * 得到对象
				 */
				Wallpaper wallpaper =  (Wallpaper) util1.getObject( Wallpaper.class);
				if(wallpaper!=null)
				{
					/**
					 * 反射得到字段的内容
					 */
					Field[] fs = Wallpaper.class.getFields();
					for (int i = 0; i < fs.length; i++) {
						String s = fs[i].getName()+"="+fs[i].get(wallpaper);
						sb.append(s).append("\n");
					}
				}else{
					sb.append("wallpaper is null");
				}
				text.setText(sb.toString());
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
		
	}
}


 

上面的代码,复制测试就可以了,本人也只是对反射机制了解一个基础,更深层次的还需要深入的研究的!
如果大家使用这个工具类有什么问题,可以随时联系我的 !QQ:84095015

 <优化了上次存在的一个空对象问题>

原文地址:https://www.cnblogs.com/springskyhome/p/3689945.html