map 与 json 格式之间转换

前后台交互时采用JSON格式进行交互。前端接收到请求数据后保存为MAP格式。传给后台时采用JSON格式。
分别写了二种方法进行比较处理。

- 方法一:

        String strRecvPage = "{";
        Set keySet = paramMap.keySet();
        for(Iterator it =keySet.iterator();it.hasNext();){
            String key = it.next();
            String value = paramMap.get(key);
            System.out.print(key + ":" + value + "\n");
            strRecvPage += "\"" + key+ "\":";
            strRecvPage += "\"" + value+ "\",";
        }

        if (strRecvPage.lastIndexOf(",") > 0){
            strRecvPage = strRecvPage.substring(0, strRecvPage.lastIndexOf(","));
        }
        strRecvPage += "}";
//out :
{"pgRetUrl":"http://127.0.0.1:8080/PayTestSuites/callLBM/callBack?device=PC","certType":"01","bgRetUrl":"http://www.baidu.com","ordSeqId":"00000000000000002017080600000005","respmsg":"手机通道暂不支持该银行!","cardNo":"6210816270031359369","respcode":"9999","device":"PC","certNo":"331001190007020612","appSysId":"90000","cardPhone":"13800138000","ordDate":"20170806","usrName":"台州市","signature":"e1a0e2cb6749b0f23a6e2fcd00bb1317"}        
  • 方法二:
    //map2json方法
    public static JSONObject map2Json(HashMap<String,String> map){  
        JSONObject json = new JSONObject();  
        Set<String> set = map.keySet();  
        for (Iterator<String> it = set.iterator();it.hasNext();) {  
            String key = it.next();  
            json.put(key, map.get(key));  
        }         
        return json;  
    }

//方法调用处
String strJson = map2Json(paramMap).toString();

//out:
{"pgRetUrl":"http://127.0.0.1:8080/PayTestSuites/callLBM/callBack?device=PC","certType":"01","bgRetUrl":"http://www.baidu.com","ordSeqId":"00000000000000002017080600000005","respmsg":"手机通道暂不支持该银行!","cardNo":"6210816270031359369","respcode":"9999","device":"PC","certNo":"331001190007020612","appSysId":"90000","cardPhone":"13800138000","ordDate":"20170806","usrName":"台州市","signature":"e1a0e2cb6749b0f23a6e2fcd00bb1317"}

你可能感兴趣的:(Java)