JsonUtils工具类

public class JsonUtils {


public static void printTimeObject(Object obj, HttpServletResponse response, JsonConfig jsonConfig) throws IOException {
JSONObject jsonObject = JSONObject.fromObject(obj, jsonConfig);
setContentType(response);
response.getWriter().print(jsonObject.toString());
}

public static void printObject(Object obj, HttpServletResponse response) throws IOException {
JSONObject jsonObject = JSONObject.fromObject(obj);
setContentType(response);
response.getWriter().print(jsonObject.toString());
}

/**
*
* @param value
* @param response
* @throws IOException
*/
public static void printString(String value, HttpServletResponse response) throws IOException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("value", value);
JsonUtils.setContentType(response);
response.getWriter().print(jsonObject);
}


@SuppressWarnings("unchecked")
public static void printArray(List list, HttpServletResponse response) throws IOException {
JSONArray json = JSONArray.fromObject(list);
setContentType(response);
response.getWriter().print(json.toString());
}

/**
* @param response
*/
private static void setContentType(HttpServletResponse response) {
response.setContentType("text/html;charset=UTF-8");
}

@SuppressWarnings("unused")
public static String readJSONStringFromRequest(HttpServletRequest request){
StringBuffer json = new StringBuffer();
String line = null;
String result = "";
try {
request.setCharacterEncoding("UTF-8");
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
while((line = reader.readLine()) != null) {
json.append(line);
}
result = java.net.URLDecoder.decode(json.toString(), "UTF-8");
System.out.println(result);
}
catch(Exception e) {
System.out.println(e.toString());
}
return result;
}

public static String readJSONString(HttpServletRequest request){
String result = "";
try {
InputStream in = request.getInputStream();
int len = request.getContentLength();
if (len <= 0) len = 2048;
byte[] tmp = new byte[2048];
byte[] buffer = new byte[len];
int totalLen = 0;
while (true) {
int readLen = in.read(tmp, 0, 2048);
if (readLen <= 0) break;
if ((readLen + totalLen) > len) {
len = len + readLen + 2048; // 扩大缓冲区
byte[] aa = new byte[len];
System.arraycopy(buffer, 0, aa, 0, totalLen);
buffer = aa;
}
System.arraycopy(tmp, 0, buffer, totalLen, readLen);
totalLen = totalLen + readLen;
}
result = new String(buffer,"UTF-8");
}catch(Exception e) {
System.out.println(e.toString());
}
return result;

}

}

posted @ 2016-01-05 14:55  java高级技术汇  阅读(1045)  评论(0编辑  收藏  举报