import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.JSONUtils;

public class JsonParser {

/**

  • json字符串 转成 map
  • @param jsonStr
  • @return
  • @throws Exception
    */
    public static HashMap parse(String jsonStr) {
    if (jsonStr == null || "".equals(jsonStr)) { return null; }
    HashMap retMap = null;
    try {
    retMap = new HashMap();
    JSONObject json = JSONObject.fromObject(jsonStr);
    Map tmpMap = (Map) JSONObject
    .toBean(json, Map.class);
    for (Map.Entry entry : tmpMap.entrySet()) {
    JsonValue tmp = parseRec(entry.getValue(), 0);
    retMap.put(entry.getKey(), tmp);
    }
    }
    catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return retMap;
    }

    /**

  • json字符串 转成 List
  • @param jsonStr
  • @return
  • @throws Exception
    */
    public static List> parseList(String jsonStr) {
    if (jsonStr == null || "".equals(jsonStr)) { return null; }

    List> retList = new ArrayList>();

    JSONArray data = JSONArray.fromObject(jsonStr);
    for (int i = 0; i < data.size(); i++) {
    HashMap retMap = new HashMap();

    JSONObject json = (JSONObject) data.get(i);
    Map tmpMap = (Map) JSONObject
    .toBean(json, Map.class);

    for (Map.Entry entry : tmpMap.entrySet()) {
    JsonValue tmp = parseRec(entry.getValue(), 0);
    retMap.put(entry.getKey(), tmp);
    }
    retList.add(retMap);
    }
    return retList;
    }

    /**

  • HashMap map 转成 json字符串
  • @param jsonStr
  • @return
  • @throws Exception
    */
    public static String parse(HashMap map) {
    HashMap retMap = new HashMap();
    for (Map.Entry entry : map.entrySet()) {
    Object tmp = parseJsonValueRec(entry.getValue(), 0);
    retMap.put(entry.getKey(), tmp);
    }
    JsonConfig jc = new JsonConfig();
    return JSONObject.fromObject(retMap, jc).toString();
    }

    /**

  • List> list 转成 json字符串
  • @param jsonStr
  • @return
  • @throws Exception
    */
    public static String parse(List> list) {
    List> tmpList = new ArrayList>();

    for (HashMap map : list) {
    HashMap retMap = new HashMap();
    for (Map.Entry entry : map.entrySet()) {
    Object tmp = parseJsonValueRec(entry.getValue(), 0);
    retMap.put(entry.getKey(), tmp);
    }
    tmpList.add(retMap);
    }
    JSONArray json = new JSONArray();
    json.addAll(tmpList);
    return json.toString();
    }

    /**

  • 构建json
  • @param map
  • @return
    */
    public static String parse(Map map) {
    JsonConfig jc = new JsonConfig();
    return JSONObject.fromObject(map, jc).toString();
    }

    对了,json的版本我用的是json-lib-2.4-jdk15.jar