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

来源:互联网 发布:性别歧视 知乎 编辑:程序博客网 时间:2024/06/05 16:58
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;}}

1 0
原创粉丝点击