java数据类型转换____request请求参数类型转换

package com.cnse.convert.json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

public class Snippet {
	/**
	 * ================================================读取request流中传递的json串型参数=================================
	 * 请求参数为传递过来的json串 {"user":"zhangsan","password":"123456"}
	 * @param request
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	public String parseRequestJson(HttpServletRequest request) throws IOException, UnsupportedEncodingException {
		String requestJsonStr = "";
		try {
			// 读取请求内容
			BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
			String line = null;
			StringBuilder sb = new StringBuilder();
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			requestJsonStr = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return requestJsonStr;
	}
	
	protected Object jsonStrToBean(String jsonStr,Class<?> clazz) throws JsonSyntaxException, UnsupportedEncodingException, IOException {
		Gson g = new Gson();
		Object obj = null;
		try {
			obj = g.fromJson(jsonStr, clazz);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
	/**
	 * ================================================读取request流中传递的xml串型参数=================================
	 * 请求参数为传递过来的xml型参数
	 * <xml> 
	 * <FromUserName>zhangsan</FromUserName> <CreateTime>123</CreateTime>  
	 * <MsgType>Music</MsgType>  <FuncFlag>1</FuncFlag>  <Content>this is teset </Content>	
	 * </xml>
	 * @param request
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */	
	public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
		// 将解析结果存储在HashMap中
		Map<String, String> map = new HashMap<String, String>();
		// 从request中取得输入流
		InputStream inputStream = request.getInputStream();
		// 读取输入流
		SAXReader reader = new SAXReader();
		Document document = reader.read(inputStream);
		// 得到xml根元素
		Element root = document.getRootElement();
		// 得到根元素的所有子节点
		@SuppressWarnings("unchecked")
		List<Element> elementList = root.elements();
		// 遍历所有子节点
		for (Element e : elementList){
			map.put(e.getName(), e.getText());
		}
		// 释放资源
		inputStream.close();
		inputStream = null;
		return map;
	}
	
}

posted @ 2017-02-27 09:23  蜜獾互联网  阅读(5)  评论(0编辑  收藏  举报  来源