Java解析POST提交的json数据工具类

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/wangli61289/article/details/53695570

工具类用于解析通过网络传输json数据的参数

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.dianping.cat.Cat;

/*
 * 解析POST提交的json数据工具类
 */
public class RequestUtil {

	private static Logger log = Logger.getLogger(RequestUtil.class);

	/**
	 * 解析request的输入流
	 * @param request
	 * @return 请求的json字符串
	 */
	public static synchronized String getRequestBody(HttpServletRequest request) {
		String str = null;
		try {
			str = IOUtils.toString(request.getInputStream());
		} catch (IOException e) {
			log.info(e.getMessage());
			Cat.logError(e);
			e.printStackTrace();
		}
		return str;
	}
	
	

	/**
	 * 解析request的json数据
	 * @param request
	 * @return Map
	 */
	public static synchronized Map<String, Object> parseRequest(
			HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>() ;
		try {
			String req = getRequestBody(request);
			if(StringUtilsExtends.isNotBlank(req)){
				JSONObject jsonObject = JSONObject.fromObject(req);
				for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
					String key = (String) iter.next();
					map.put(key, jsonObject.get(key));
				}
			}
			log.info(map);

		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			Cat.logError(e);
		}
		return map;
	}
	
	
	

	/**
	 * 获取map的value
	 * @param map
	 * @param key
	 * @return 
	 */
	public static Object getRequestBodyValue(
			Map<String, Object> map, String key) {
		if (map != null && StringUtils.isNotBlank(key) && map.containsKey(key)) {
			return map.get(key);
		}
		return null;
	}

}


controller中的使用

@Controller
public class userController {

	private Logger log = Logger.getLogger(this.getClass());

	@RequestMapping(value="/getUser",method=RequestMethod.POST)
	@ResponseBody
	public String getSipAccount(HttpServletRequest req){
		try {
			Map<String, Object> paramMap = RequestUtil.parseRequest(req);
			String userName = (String) RequestUtil.getRequestBodyValue(paramMap,
					"userName");
            //do something
		} catch (Exception e) {
			e.printStackTrace();
		}
		return userName;
	}
}



展开阅读全文

没有更多推荐了,返回首页