总结了日常开发中对Json格式的处理,需要下载json相关Jar;这里提供下主要Jar
json-lib-2.2.3-jdk13.jar
import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.xml.XMLSerializer; /** * Json串处理工具类 * json,list,map等之间的各种转化 * @author * @version 2.0 create at,2009-2-12 * */ public class JsonUtil { /** * 将json格式的字符串转化为jsonobject * @param str * @return * @throws ApplicationException */ public static JSONObject stringToJsonObject(String str) throws ApplicationException { JSONObject jsonObject = null; if (Validator.isNotNull(str)) { try{ jsonObject = JSONObject.fromObject(str); }catch(Exception ex){ throw new ApplicationException("要转化的字符串格式不对,必须为json格式!"); } } return jsonObject; } /** * 从指定的List<map>对象中获取要设置的值后组装成返回给前台的JSON对象字符串. * 主要用于给前台分页grid组装数据 * @param list list<map>从数据库中查询出来的数据 * @param count 总数 * @return */ @SuppressWarnings("unchecked") public static String fromMap(List list, int count) { //将list<map>转化为jsonarray JSONArray options = formListArray(list); JSONObject result = new JSONObject(); result.put("result", options); result.put("totalCount", count); return result.toString(); } /** * 将Map<String,String>转化为JSONObject格式的字符串 * @param map * @return {"success":true,"result":{}} */ public static String fromMapToJson(Map<String, String> map) { Iterator<String> it = map.keySet().iterator(); JSONObject jsonObject = new JSONObject(); JSONObject json = new JSONObject(); while (it.hasNext()) { String key = (String) it.next(); jsonObject.put(key.toLowerCase(), map.get(key)); } json.put("success", true); json.put("result", jsonObject.toString()); return json.toString(); } /** * 将list<map>转化为jsonobject格式的字符串 * @param list * @return {"result":{...}} */ @SuppressWarnings("unchecked") public static String fromListMap(List list) { JSONArray options = new JSONArray(); for (Object obj : list) { Iterator it = ((Map) obj).keySet().iterator(); Object value; JSONObject option = new JSONObject(); while (it.hasNext()) { String key = (String) it.next(); value = ((Map) obj).get(key); value = value != null ? value : ""; option.put(key.toLowerCase(), value); } options.add(option); } JSONObject result = new JSONObject(); result.put("result", options.toString()); return result.toString(); } /** * 从list<map>转化为treenode的json * @param list * @return */ @SuppressWarnings("unchecked") public static String toAsynTreeJson(List list) { JSONArray ja = new JSONArray(); for (Object obj : list) { Iterator it = ((Map) obj).keySet().iterator(); JSONObject option = new JSONObject(); while (it.hasNext()) { String key = (String) it.next(); Object value = ((Map) obj).get(key); key = key.toLowerCase(); value = value == null ? "" : value.toString(); //是否含有带checkbox的treenode if (key.equals("checked")) { boolean check = value.equals("1") ? true : false; option.put("checked", check); } //是为叶子节点还是为非叶子节点 else if("leaf".equals(key)){ boolean leaf = value.toString().trim().equals("1")?true:false; option.put("leaf", leaf); }else if("draggable".equals(key)){ boolean draggable = value.toString().trim().equals("1")?true:false; option.put("draggable", draggable); } else option.put(key, value); } ja.add(option); } return ja.toString(); } /** * 将list<map>转化为jsonarray * 此JSONArray的格式将会是这样[{},{}] * @param list * @return */ @SuppressWarnings("unchecked") public static JSONArray formListArray(List list) { JSONArray options = new JSONArray(); for (Object obj : list) { Iterator it = ((Map) obj).keySet().iterator(); JSONObject option = new JSONObject(); while (it.hasNext()) { String key = (String) it.next(); Object value = ((Map) obj).get(key); value = value != null ? value : ""; option.put(key.toLowerCase(), value); } options.add(option); } return options; } /** * 从List<Model>转化成jsonArray * list中装的对象为具体的po * @param list * @return */ @SuppressWarnings("unchecked") public static JSONArray formListModelArray(List list){ JSONArray options = new JSONArray(); for (Object obj : list) { options.add(obj); } return options; } /** * 将JSONArray逆向转化为List list中可以为任何元素, * @param json 符合JSONArray格式的字符串 * 可以是很复杂的格式,如[{},[],{a:[],b:{},c:{cc:[]...}},'test'] * @return */ @SuppressWarnings("unchecked") public static List JSONArrayConvertList(String json) { ArrayList list = new ArrayList(); JSONArray ja = JSONArray.fromObject(json); populateArray(ja, list); return list; } @SuppressWarnings("unchecked") private static void populateArray(JSONArray jsonArray, List list) { //循环遍历jsonarray for (int i = 0; i < jsonArray.size(); i++) { if (jsonArray.get(i).getClass().equals(JSONArray.class)) { //如果元素是JSONArray类型 ArrayList _list = new ArrayList(); list.add(_list); //递归遍历,此为深度遍历,先把最内层的jsonobject给遍历了 populateArray(jsonArray.getJSONArray(i), _list); } else if (jsonArray.get(i).getClass().equals(JSONObject.class)) { //如果是JSONObject类型 HashMap _map = new HashMap(); list.add(_map); //遍历JSONObject populate(jsonArray.getJSONObject(i), _map); } else { //如果都不是的话就直接加入到list中 list.add(jsonArray.get(i)); } } } @SuppressWarnings("unchecked") private static Map populate(JSONObject jsonObject, Map map) { for (Iterator iterator = jsonObject.entrySet().iterator(); iterator .hasNext();) { String entryStr = String.valueOf(iterator.next()); String key = entryStr.substring(0, entryStr.indexOf("=")); if (jsonObject.get(key).getClass().equals(JSONObject.class)) { HashMap _map = new HashMap(); map.put(key, _map); populate(jsonObject.getJSONObject(key), _map); } else if (jsonObject.get(key).getClass().equals(JSONArray.class)) { ArrayList list = new ArrayList(); map.put(key, list); populateArray(jsonObject.getJSONArray(key), list); } else { map.put(key, jsonObject.get(key)); } } return map; } /** * Map转换成JSONObject * @param map * @return */ @SuppressWarnings("unchecked") public JSONObject populateToJsonObject(Map map) { JSONObject temp = new JSONObject(); Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Entry entry = (Entry) iter.next(); String key = entry.getKey().toString(); String value = entry.getValue() == null ? "" : entry.getValue().toString(); temp.put(key, value); } return temp; } /** *将json转化为xml **/ public static String jsonToXml(JSON json,Boolean appendHint){ XMLSerializer xmlSerializer = new XMLSerializer(); xmlSerializer.setTypeHintsEnabled(appendHint); xmlSerializer.setRootName("root"); return xmlSerializer.write(json); } /** *将xml转化为json **/ public static JSON xmlToJson(String xml){ XMLSerializer xmlSerializer = new XMLSerializer(); JSON json = xmlSerializer.read(xml); return json; } }