Json数据转化为map,list

import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public static Map<Integer, String> parseJSON2Map(String str) {
        if (StringUtil.isEmpty(str)) {
            logger.error("Invalid param:jsonAnswer!");
            return Collections.EMPTY_MAP;
        }
        Map<Integer, String> resultMap;
        try {
            JSONObject jsonObject = new JSONObject(str);
            if (jsonObject == null) {
                logger.error("JSONObject is null!String is {}", str);
                return Collections.EMPTY_MAP;
            }
            resultMap = new HashMap<Integer, String>();
            String[] keys = JSONObject.getNames(jsonObject);
            for (String key : keys) {
                resultMap.put(Integer.parseInt(key), jsonObject.get(key).toString());
            }

        } catch (JSONException e) {
            e.printStackTrace();
            logger.error("Parse fail!Cause:{}", e.getMessage());
            return Collections.EMPTY_MAP;
        }
        return resultMap;
    }

    public static List<String> parseJSON2StrList(String str) {
        if (StringUtil.isEmpty(str)) {
            logger.error("Invalid param:jsonAnswer!");
            return Collections.EMPTY_LIST;
        }
        List<String> resultList = null;
        try {
            JSONObject jsonObject = new JSONObject(str);
            if (jsonObject == null) {
                logger.error("JSONObject is null!String is {}", str);
                return Collections.EMPTY_LIST;
            }
            resultList = new LinkedList<String>();
            String[] keys = JSONObject.getNames(jsonObject);
            Arrays.sort(keys);
            for (String key : keys) {
                resultList.add(new StringBuffer(key).append(".").append(jsonObject.get(key)).toString());
            }
            logger.debug("ResultList is {}", resultList);

        } catch (JSONException e) {
            e.printStackTrace();
            logger.error("Parse fail!Cause:{}", e.getMessage());
            return Collections.EMPTY_LIST;
        }
        return resultList;
    }

posted on 2012-11-26 18:27  JaredYang  阅读(386)  评论(0)    收藏  举报

导航