Json的解析

我在一般 :

if (Constants.HttpResponseStatus.success.equals(obj.getCode())) {
try {
mDatasOne.clear();
mDatasTwo.clear();

在成功拿到数据之前, 要在清除操作;否则会重复添加; 


JSONObject result = obj.getResult();
Logs.e("result:"+result);

在拿到json 数据的时候, 可以打印一下 ; 看看返回的数据是否正确 ;


有一次 ,服务器给我返回的数据是 有可能是一个集合, 还有情况是bean对象 ; 这时我们就需要判断了;

if (map.get("firstLevel") instanceof JSONObject) {

}

我就强转成 JSONObject ,否则就有可能是 JSONArray

使用范例 :

JSONObject result = obj.getResult();
Logs.e("result:"+result);
preUrl = result.getString("preUrl");


List<ShiShiMol> jsonArrayToListBean = JSONUtils.jsonArrayToListBean(ShiShiMol.class,result.getJSONArray("mapListOfTD"));
// 解析显示数据
setContentData(jsonArrayToListBean, preUrl);
// 
 if (StringUtils.isStrongEmpty(dyUuid)) {
// //firstLevel 一级评论  是评论
JSONArray jsonArray = result.getJSONArray("commentList");


List<Map<String,Object>> parseJSON2List = JSONUtils.parseJSON2List(jsonArray);

for (int i = 0; i < parseJSON2List.size(); i++) {
Map<String, Object> map = parseJSON2List.get(i);
JSONObject jsonObject=(JSONObject) map.get("firstLevel");

ShiShiComment shiShiComment = JSONUtils.jsonObjectToBean(ShiShiComment.class,jsonObject);
mDatasOne.add(shiShiComment);

JSONArray  jsonarray= (JSONArray) map.get("secondLevel");
// [] 
//这个是 二级评论,每个一级评论里面都有可能有多个二级评论内容
List<ShiShiComment> listTwo = JSONUtils.jsonArrayToListBean(ShiShiComment.class, jsonarray);

if (null !=listTwo && listTwo.size()>0) {
mDatasTwo.add(listTwo);
}
} 



package com.free.shishi.http.base;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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

import com.free.shishi.model.ShiShiMol;
import com.free.shishi.utils.StringUtils;
import com.google.gson.Gson;

/**
 * 
 * JSON 工具类
 * 
 * @author oceangray
 *
 */
public class JSONUtils {
	
	/**
	 * 把JSON对象转换为bean对象
	 * <p>
	 * 注意:对象类型现在处理的都是String类型,如果有其他类型还需要处理
	 * 
	 * @param clazz
	 * @param jsonObject
	 * @return
	 */
	public static <T> T jsonObjectToBean(Class<T> clazz, JSONObject jsonObject) {
		T entity = null;
		try {
			entity = clazz.newInstance();
			for (Field field : clazz.getDeclaredFields()) {
				String fieldName = field.getName();
				if (Modifier.isStatic(field.getModifiers())) {
					continue;
				}
				if (StringUtils.isEmpty(fieldName)) {
					continue;
				}
				if ("serialVersionUID".equals(fieldName)) {
					continue;
				}
				if ("this".indexOf(fieldName) != -1) {
					continue;
				}
				field.setAccessible(true);
				Class<?> fieldType = field.getType();
				if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {
					// Integer value=getJSONString(jsonObject,
					// fieldName)==""?0:Integer.valueOf(getJSONString(jsonObject,
					// fieldName));
					Integer value;
					if (getJSONString(jsonObject, fieldName).equalsIgnoreCase(
							"")) {
						value = 0;
					} else {
						value = Integer.valueOf(getJSONString(jsonObject,
								fieldName));
					}
					field.set(entity, value);
				} else if ((Long.TYPE == fieldType)
						|| (Long.class == fieldType)) {
					String valuestr = getJSONString(jsonObject, fieldName);
					Long value;
					if (valuestr.equalsIgnoreCase("")) {
						value = 0L;
					} else {
						value = Long.valueOf(getJSONString(jsonObject,
								fieldName));
					}
					// Long value=getJSONString(jsonObject,
					// fieldName)==""?0L:Long.valueOf(getJSONString(jsonObject,
					// fieldName));
					field.set(entity, value);
				} else if ((JSONObject.class == fieldType)) {
					field.set(entity, getJSONObject(jsonObject, fieldName));
				} else if ((JSONArray.class == fieldType)) {
					field.set(entity, getJSONArray(jsonObject, fieldName));
				} else {
					String value = getJSONString(jsonObject, fieldName);
					field.set(entity, value);
				}
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return entity;
	}

	/**
	 * json节点转换为jsonObject
	 * 
	 * @param jsonObject
	 * @param nodeName
	 * @return
	 */
	private static JSONObject getJSONObject(JSONObject jsonObject,
			String nodeName) {
		if (jsonObject.isNull(nodeName)) {
			return null;
		} else {
			try {
				return jsonObject.getJSONObject(nodeName);
			} catch (JSONException e) {
				e.printStackTrace();
				return null;
			}
		}
	}

	/**
	 * json节点转换为jsonArray
	 * 
	 * @param jsonObject
	 * @param nodeName
	 * @return
	 */
	private static JSONArray getJSONArray(JSONObject jsonObject, String nodeName) {
		if (jsonObject.isNull(nodeName)) {
			return null;
		} else {
			try {
				return jsonObject.getJSONArray(nodeName);
			} catch (JSONException e) {
				e.printStackTrace();
				return null;
			}
		}
	}

	/**
	 * 获取JOSN对象对应节点字符串
	 * 
	 * @param jsonObject
	 * @param nodeName
	 * @return
	 */
	public static String getJSONString(JSONObject jsonObject, String nodeName) {
		if (jsonObject.isNull(nodeName)) {
			return "";
		} else {
			try {
				return jsonObject.getString(nodeName);
			} catch (JSONException e) {
				e.printStackTrace();
				return "";
			}
		}
	}

	/**
	 * 将JsonArray转换成ArrayList
	 * 
	 * @param array
	 * @return
	 */
	public static ArrayList<String> parseToArrayList(JSONArray array) {
		if (array == null) {
			return null;
		}

		int len = array.length();
		ArrayList<String> list = new ArrayList<String>();
		for (int i = 0; i < len; i++) {
			list.add(array.optString(i));
		}

		return list;
	}

	/**
	 * jsonArray 字符串转换为 ArrayList
	 * 
	 * @param jsonString
	 * @return
	 */
	public static ArrayList<String> jsonArrayStringToStringArray(
			String jsonString) {
		if (!StringUtils.isEmpty(jsonString)) {
			try {
				JSONArray array = new JSONArray(jsonString);
				return parseToArrayList(array);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return new ArrayList<String>();
	}

	/**
	 * jsonarray 转换为list bean
	 * 
	 * @param clazz
	 * @param jsonArray
	 * @return
	 */
	public static <T> List<T> jsonArrayToListBean(Class<T> clazz,JSONArray jsonArray) {
		List<T> list = new ArrayList<T>();
		for (int index = 0; index < jsonArray.length(); index++) {
			try {
				T t = jsonObjectToBean(clazz, jsonArray.getJSONObject(index));
				list.add(t);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	/**
	 * 将json 数组转换为Map 对象
	 * 
	 * @param jsonString
	 * @return
	 */
	public static Map<String, Object> getMap(JSONObject jsonObject) {
		try {
			// jsonObject = new JSONObject(jsonString);
			// @SuppressWarnings("unchecked")
			Iterator<String> keyIter = jsonObject.keys();
			String key;
			Object value;
			Map<String, Object> valueMap = new HashMap<String, Object>();
			while (keyIter.hasNext()) {
				key = (String) keyIter.next();
				value = jsonObject.get(key);
				valueMap.put(key, value);
			}
			return valueMap;
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static <T> List<Map<String, T>> parseJSON2List(JSONArray jsonArray) {
		// JSONArray jsonArr = JSONArray.fromObject(jsonStr);
		List<Map<String, T>> list = new ArrayList<Map<String, T>>();
		for (int index = 0; index < jsonArray.length(); index++) {
			try {
				JSONObject jsonObject = jsonArray.getJSONObject(index);
				Map<String, T> map = (Map<String, T>) getMap(jsonObject);
				list.add(map);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return list;
	}


	/**
	 * jsonarray 转换为list bean
	 * 
	 * @param clazz
	 * @param jsonArray
	 * @return
	 */
	public static <T> List<T> jsonArrayToListBean(Class<T> clazz,
			String jsonString) {
		List<T> list = new ArrayList<T>();
		JSONArray jsonArray;
		try {
			jsonArray = new JSONArray(jsonString);
			for (int index = 0; index < jsonArray.length(); index++) {
				try {
					T t = jsonObjectToBean(clazz,
							jsonArray.getJSONObject(index));
					list.add(t);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		return list;
	}

	/**
	 * 把json字符串变成集合 params: new TypeToken<List<yourbean>>(){}.getType(),
	 * 
	 * @param json
	 * @param type
	 *            new TypeToken<List<yourbean>>(){}.getType()
	 * @return
	 */
	public static List<?> parseJsonToList(String json, Type type) {
		Gson gson = new Gson();
		List<?> list = gson.fromJson(json, type);
		return list;
	}

}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值