package com.chenyang.nse.bussiness.tools.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;

public class BufferUtil {
   public static Object parseBuffer(HttpServletRequest request, String objType) throws IOException {
      request.setCharacterEncoding("UTF-8");
      BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
      String jsonStr = null;
      StringBuilder result = new StringBuilder();

      try {
         while((jsonStr = reader.readLine()) != null) {
            result.append(jsonStr);
         }
      } catch (IOException e) {
         e.printStackTrace();
      }

      reader.close();
      switch (objType) {
         case "JSONObject":
            return parse2JSONObject(result);
         case "Map":
            return parse2Map(result);
         default:
            return null;
      }
   }

   private static JSONObject parse2JSONObject(StringBuilder result) {
      JSONObject jsonObject = JSONObject.parseObject(result.toString());
      return jsonObject;
   }

   private static Object parse2Map(StringBuilder result) {
      HashMap<String, Object> hashMap = (HashMap)JSON.parseObject(result.toString(), HashMap.class);
      return hashMap;
   }
}
