JSON处理工具类

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.ListOrderedMap;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.*;

/**
 * 处理json的工具类.
 */
public class JsonUtil {
    /**
     * json转换list.
     * 
详细说明 * * @param jsonStr json字符串 * @return List> list * @throws */ public static List> parseJSON2List(String jsonStr) { JSONArray jsonArr = JSONArray.fromObject(jsonStr); List> list = new ArrayList>(); Iterator it = jsonArr.iterator(); while (it.hasNext()) { JSONObject json2 = it.next(); list.add(parseJSON2Map(json2.toString())); } return list; } /** * json转换map. *
详细说明 * * @param jsonStr json字符串 * @return Map 集合 * @throws */ public static Map parseJSON2Map(String jsonStr) { ListOrderedMap map = new ListOrderedMap(); //最外层解析 JSONObject json = JSONObject.fromObject(jsonStr); for (Object k : json.keySet()) { Object v = json.get(k); //如果内层还是数组的话,继续解析 if (v instanceof JSONArray) { List> list = new ArrayList>(); Iterator it = ((JSONArray) v).iterator(); while (it.hasNext()) { JSONObject json2 = it.next(); list.add(parseJSON2Map(json2.toString())); } map.put(k.toString(), list); } else { map.put(k.toString(), v); } } return map; } /** * 通过HTTP获取JSON数据. *
通过HTTP获取JSON数据返回list * * @param url 链接 * @return List> list * @throws */ public static List> getListByUrl(String url) { try { //通过HTTP获取JSON数据 InputStream in = new URL(url).openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } return parseJSON2List(sb.toString()); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 通过HTTP获取JSON数据. *
通过HTTP获取JSON数据返回map * * @param url 链接 * @return Map 集合 * @throws */ public static Map getMapByUrl(String url) { try { //通过HTTP获取JSON数据 InputStream in = new URL(url).openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } return parseJSON2Map(sb.toString()); } catch (Exception e) { e.printStackTrace(); } return null; } /** * map转换json. *
详细说明 * * @param map 集合 * @return String json字符串 * @throws */ public static String mapToJson(Map map) { Set keys = map.keySet(); String key = ""; String value = ""; StringBuffer jsonBuffer = new StringBuffer(); jsonBuffer.append("{"); for (Iterator it = keys.iterator(); it.hasNext(); ) { key = (String) it.next(); value = map.get(key); jsonBuffer.append(key + ":" + "\"" + value + "\""); if (it.hasNext()) { jsonBuffer.append(","); } } jsonBuffer.append("}"); return jsonBuffer.toString(); } }

 

你可能感兴趣的:(Java工具类)