首先有个json数据;
jsonData = "{success:false, msg:'缺少dataType参数!'}";
或者调用下面的方法,让她变成json数据
public static String toJson(boolean success, String key, String value) {
Map<String, String> jsonMap = new HashMap<String, String>();
jsonMap.put(key, value);
return toJson(success, jsonMap);
}
public static String toJson(boolean success, Map<String, String> jsonMap) {
StringBuffer buffer = new StringBuffer();
if (success) {
buffer.append("{success:true");
} else {
buffer.append("{success:false");
}
if (jsonMap.size() > 0) {
buffer.append(",");
for (String key : jsonMap.keySet()) {
if (!key.equals("class"))
buffer.append(key + " : '" + jsonMap.get(key) + "',");
}
// 去掉最后一个','
buffer.deleteCharAt(buffer.length() - 1);
}
buffer.append("}");
return buffer.toString();
}
jsonData = "{success:false, msg:'缺少dataType参数!'}";
或者:
这样json数据就生成了,接下来,将json输出到前台
/**
* JSON格式的输出
*/
protected void writeJSON(String jsonData) {
try {
outputAjaxJsonData(jsonData);
} catch (Exception ex) {
logger.error("输出信息报错", ex);
}
}
/**
* 将数据以ajax方式输出到页面
*
* @param String 输出到界面的信息
*/
protected void outputAjaxJsonData(String outputString) {
try {
HttpServletResponse response = this.getResponse();
response.setContentType("text/json");
response.setCharacterEncoding("utf-8");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write(outputString);
response.getWriter().close();
} catch (Exception ex) {
logger.error("HttpServletResponse 输出流报错", ex);
}
}