1. 程式人生 > >java中map和表單字串相互轉換

java中map和表單字串相互轉換

一、需求

serialnum=123456&data=357c0a04f&enable=true&key=b5b806d0dc9

帶有&分割的字串,轉化為map的key、value型別儲存,反之也行。

二、程式碼

import java.util.HashMap;
import java.util.Map;

public class TestMapForm {
    /**
     * hashMap 轉化成表單字串
     *
     * @param map
     * @return
     */
    public static String map2Form(HashMap<String, String> map) {
        StringBuilder stringBuilder = new StringBuilder();
        if (map == null) {
            return stringBuilder.toString();
        } else {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            return stringBuilder.substring(0, stringBuilder.length() - 1);
        }
    }
    /**
     * 表單字串轉化成 hashMap
     *
     * @param orderinfo
     * @return
     */
    public static HashMap<String, String> form2Map( String orderinfo) {
        String listinfo[];
        HashMap<String, String> map = new HashMap<String, String>();
        listinfo = orderinfo.split("&");
        for(String s : listinfo)
        {
            String list[]  = s.split("=");
            if(list.length>1)
            {
                map.put(list[0], list[1]);
            }
        }
        return map;
    }

    public static void main(String[] args) throws Exception {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("SerialNumber", "123456");
        map.put("Enable", "true");
        map.put("Bytes", "62bb");
        map.put("HashCode", "a9cf");
        String strInfo = map2Form(map);
        System.out.println(strInfo);

        HashMap<String, String> OutMap = form2Map(strInfo);
        //獲取 responseCode
        String responseCode = map.get("HashCode");
        System.out.println(responseCode);
    }
}