/** * 将对象分装为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) { Log.e("jsonUtil--Enclose", e.getMessage()); return e.getMessage(); } }
时间: 2024-10-22 04:38:03