新增:一个方法将Object封装为Json字符串,解决用户输入中带有特殊字符的问题
import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONStringer; import org.json.JSONTokener; import cc.util.android.core.LogUtil; import android.util.Log; /** * 解析多层次Json字符串,封装多层Json,避免字符串中有特殊字符而出现的错误 * @author wangcccong * @version 1.140122 * create at: Fri, 13 Jun 2014 * update at: Mon, 1 Sep 2014 */ public class JsonUtil { private final static String regex = "\"([^\\\" ]+?)\":"; /** * 一个方法解析多层json数据 json + 正则 + 递归 * @see {@link java.util.regex.Matcher}, {@link java.util.regex.Pattern} * @param jsonStr * @return {@link java.util.Map} or {@link java.util.List} or {@link java.lang.String} */ public static Object jsonParse(final String jsonStr) { if (jsonStr == null) throw new NullPointerException("JsonString shouldn't be null"); try { if (isJsonObject(jsonStr)) { final Pattern pattern = Pattern.compile(regex); final Matcher matcher = pattern.matcher(jsonStr); final Map<String, Object> map = new HashMap<String, Object>(); final JSONObject jsonObject = new JSONObject(jsonStr); try { for (; matcher.find(); ) { String groupName = matcher.group(1); Object obj = jsonObject.opt(groupName); //Log.e(groupName, obj+""); if (isJsonObject(obj+"") || isJsonArray(obj+"")) { matcher.region(matcher.end() + (obj+"").replace("\\", "").length(), matcher.regionEnd()); map.put(groupName, jsonParse(obj+"")); } else { map.put(groupName, obj+""); } } } catch (Exception e) { // TODO: handle exception Log.e("object---error", e.getMessage()+"--"+e.getLocalizedMessage()); } return map; } else if (isJsonArray(jsonStr)) { List<Object> list = new ArrayList<Object>(); try { JSONArray jsonArray = new JSONArray(jsonStr); for (int i = 0; i < jsonArray.length(); i++) { Object object = jsonArray.opt(i); list.add(jsonParse(object+"")); } } catch (Exception e) { // TODO: handle exception Log.e("array---error", e.getMessage()+"--"+e.getLocalizedMessage()); } return list; } } catch (Exception e) { // TODO: handle exception Log.e("RegexUtil--regexJson", e.getMessage()+""); } return jsonStr; } /** * To determine whether a string is JsonObject {@link org.json.JSONObject} * @param jsonStr {@link java.lang.String} * @return boolean */ private static boolean isJsonObject(final String jsonStr) { if (jsonStr == null) return false; return Pattern.matches("^\\{.*\\}$", jsonStr.trim()); } /** * To determine whether a string is JsonArray {@link org.json.JSONArray}; * @param jsonStr {@link java.lang.String} * @return boolean */ private static boolean isJsonArray(final String jsonStr) { if (jsonStr == null) return false; return Pattern.matches("^\\[.*\\]$", jsonStr.trim()); } /** * 将对象分装为json字符串 (json + 递归) * @param obj 参数应为{@link java.util.Map} 或者 {@link java.util.List} * @return */ @SuppressWarnings("unchecked") public static Object jsonEnclose(Object obj) { try { if (obj instanceof Map) { //如果是Map则转换为JsonObject Map<String, Object> map = (Map<String, Object>)obj; Iterator<Entry<String, Object>> iterator = map.entrySet().iterator(); JSONStringer jsonStringer = new JSONStringer().object(); while (iterator.hasNext()) { Entry<String, Object> entry = iterator.next(); jsonStringer.key(entry.getKey()).value(jsonEnclose(entry.getValue())); } JSONObject jsonObject = new JSONObject(new JSONTokener(jsonStringer.endObject().toString())); return jsonObject; } else if (obj instanceof List) { //如果是List则转换为JsonArray List<Object> list = (List<Object>)obj; JSONStringer jsonStringer = new JSONStringer().array(); for (int i = 0; i < list.size(); i++) { jsonStringer.value(jsonEnclose(list.get(i))); } JSONArray jsonArray = new JSONArray(new JSONTokener(jsonStringer.endArray().toString())); return jsonArray; } else { return obj; } } catch (Exception e) { // TODO: handle exception LogUtil.e("jsonUtil--Enclose", e.getMessage()); return e.getMessage(); } } } //解析时使用示例 Object object = JsonUtil.jsonParse(RegexPolicy.Json, jsonStr.substring(jsonStr.indexOf("{"), jsonStr.lastIndexOf("}")+1)); if (object instanceof String) { Log.e("string", object.toString()); } else if (object instanceof Map) { @SuppressWarnings("unchecked") HashMap<String, Object> map = (HashMap<String, Object>)object; Iterator<Entry<String, Object>> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, Object> entry = iterator.next(); if (entry.getValue() instanceof List) { Log.e(entry.getKey(), entry.getValue().toString()); } else { Log.e(entry.getKey(), entry.getValue().toString()); } } } else if (object instanceof List) { Log.e("list", object.toString()); } //封装时使用示例 Map<String, Object> map = new HashMap<String, Object>(); map.put("returnCode", "0"); map.put("returnMsg", "成功"); List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); Map<String, Object> listMap = new HashMap<String, Object>(); listMap.put("test", "测试"); listMap.put("fuck", "fuck"); list.add(listMap); list.add(listMap); map.put("returnStatus", list); LogUtil.e("fuck", JsonUtil.jsonEnclose(map).toString()+"---"); //封装时结果 {"returnCode":"0","returnStatus":[{"test":"测试","fuck":"fuck"},{"test":"测试","fuck":"fuck"}],"returnMsg":"成功"}---