java關於請求參數轉Map的記錄

今天在做支付寶支付,關於異步通知結果,請求自己服務器的時候,需要接受支付寶的請求參數(類型爲參數=值&參數=值&。。。),如果一個個取太麻煩,就用 request.getParameterMap()方法把參數放到了Map中,方便對參數做操作代碼如下

public static Map<String, String> toMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 亂碼解決,這段代碼在出現亂碼時使用。
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return params;
    }

返回了一個map集合,正是我想要的東西,取值很方便,突然想到之前做微信支付的時候,接受的請求參數是XML格式,用的是對流操作取參然後轉map的,上代碼

public void returnNotify(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// 讀取參數
		InputStream inputStream;
		StringBuffer sb = new StringBuffer();
		inputStream = request.getInputStream();
		String s;
		BufferedReader in = new BufferedReader(new InputStreamReader(
				inputStream, Consts.UTF_8));
		while ((s = in.readLine()) != null) {
			sb.append(s);
		}
		in.close();
		inputStream.close();

		SortedMap<String, String> retMap = new TreeMap<String, String>();
		// 解析xml成map
		List<Map<String, String>> maplist = CommonMethodUtil.xmlToMap(sb
				.toString());
		for (Map<String, String> map : maplist) {
			for (Entry<String, String> skey : map.entrySet()) {
				retMap.put(skey.getKey(), skey.getValue());
			}
		} }

xml轉map如下

public static List<Map<String,String>> xmlToMap(String xmlStr){
		List<Map<String,String>> maplist=new ArrayList<Map<String,String>>();
		if(!"".equals(xmlStr) && null!=xmlStr){
			try {
				Document document = DocumentHelper.parseText(xmlStr);
				Element rootElement=document.getRootElement();
				@SuppressWarnings("unchecked")
				Iterator<Element> iterator=rootElement.elements().iterator();
				while(iterator.hasNext()){
					Element element=iterator.next();
					@SuppressWarnings("rawtypes")
					List rowlist=element.attributes();
					@SuppressWarnings("rawtypes")
					Iterator iter =rowlist.iterator();
					Map<String,String> map=new HashMap<String, String>();
//					map.put(element.getName(), element.getName());
					
					while(iter.hasNext()){
						AbstractAttribute elementAttr = (AbstractAttribute) iter.next();
						map.put(elementAttr.getName(), elementAttr.getValue());
					}
					map.put(element.getName(), element.getText());
					maplist.add(map);
				}
			} catch (DocumentException e) {
				e.printStackTrace();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
		return maplist;
	}

就能得到map去操作咯,是不是很方便,

另外如果傳遞的參數爲json格式可以用下面方式轉map,因爲map本身和json就類似

package com.mockCommon.controller.mock.youbi;  
  
import java.util.Map;  
  
import org.apache.commons.lang.StringUtils;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestBody;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.bind.annotation.RequestParam;  
import org.springframework.web.bind.annotation.ResponseBody;  
  
import com.mockCommon.constant.LogConstant;  
import com.mockCommon.service.mock.youbi.impl.SearchCarModelMockServiceImpl;  
  
@Controller  
public class SearchCarModelMockController {  
    @Autowired  
    private SearchCarModelMockServiceImpl searchCarModelMockServiceImpl;  
      
    @RequestMapping(value = "/vehicle", method = RequestMethod.POST)  
    @ResponseBody  
    public String searchCarModel(@RequestBody Map<String, Object> params){  
        LogConstant.runLog.info("[JiekouSearchCarModel]parameter license_no:" + params.get("license_no") + ", license_owner:" + params.get("license_owner") + ", city_code:" + params.get("city_code"));  
        String result = null;  
        if(params.get("license_no")==null || params.get("license_owner")==null|| params.get("city_code")==null){  
            return "傳遞參數不正確";  
        }  
        result = searchCarModelMockServiceImpl.getResult(params.get("license_no").toString(), params.get("license_owner").toString(), params.get("city_code").toString());  
        return result;  
    }  
}  

好了 以上就是三種常見的參數轉map的方式,如有瑕疵請多多指教


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章