servlet中将接收的参数转成Json

来源:互联网 发布:跟淘宝联盟类似的网站 编辑:程序博客网 时间:2024/05/22 10:36
public static String readJSONString(HttpServletRequest request) {
StringBuffer json = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
json.append(line);
}
if(json.length()<1){
Map<String, String[]> hm=request.getParameterMap();
if (hm!=null && hm.size()>0){
json.append(readjson(hm).toString());
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
return json.toString();
}

public static JSONObject readjson(Map<String, String[]> hm){
        JSONObject jobj = new JSONObject();
//通过循环遍历的方式获得key和value并set到JSONObject中
Iterator it = hm.keySet().iterator();
while (it.hasNext()) {
       String key = it.next().toString();
       String[] values = (String[])hm.get(key);
       jobj.put(key, values[0]);
}
        return jobj;
}

public static JSONObject readjson(HttpServletRequest request){
        JSONObject JSONObject = new JSONObject();
        Map pmap = request.getParameterMap();
//通过循环遍历的方式获得key和value并set到jsonobject中
Iterator it = pmap.keySet().iterator();
while (it.hasNext()) {
       String key = it.next().toString();
       String[] values = (String[])pmap.get(key);
       JSONObject.put(key, values[0]);
}
        return JSONObject;
}
0 0
原创粉丝点击