`
uule
  • 浏览: 6338177 次
  • 性别: Icon_minigender_1
  • 来自: 一片神奇的土地
社区版块
存档分类
最新评论

JSON工具类

 
阅读更多
package com.techson.himsnanhwa.admin.util;

import java.io.IOException;

//类1
public class JSONUtils {
	
	private static final Log log = LogFactory.getLog(JSONUtils.class);
	
	public static void sendJSON(HttpServletResponse response, String keywords, String values) {
		response.setContentType("application/json");
		response.setCharacterEncoding("utf-8");
		PrintWriter outResponse = null;
		try {
			outResponse = response.getWriter();
			JSONObject jsonObject = new JSONObject();
			jsonObject.put(keywords, values);
			outResponse.print(jsonObject.toString());
			outResponse.flush();
		} catch (IOException e) {
			log.error("json utils exception :" + e);
		} finally {
			if(outResponse != null) {
				outResponse.close();
			}
		}
	}
	
	public static void sendJSON(HttpServletResponse response,JSONObject obj) {
		response.setContentType("application/json");
		response.setCharacterEncoding("utf-8");
		PrintWriter outResponse = null;
		
		try {
			outResponse = response.getWriter();
			outResponse.print(obj.toString());
			outResponse.flush();
		} catch (IOException e) {
			log.error("json utils exception :" + e);
		} finally {
			if(outResponse != null) {
				outResponse.close();
			}
		}
	}
	
	/**
	 *  JSONUtils 传输sendJSON的处理
	 * @param response servlet的响应
	 * @param error 结果为true error =0,结果为false error = 1;
	 */
	public static void sendJSON(HttpServletResponse response, int result) {
		response.setContentType("application/json");
		response.setCharacterEncoding("utf-8");
		PrintWriter outResponse = null;
		try {
			outResponse = response.getWriter();
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("result", result);
			outResponse.print(jsonObject.toString());
			outResponse.flush();
		} catch (IOException e) {
			log.error("json utils exception :" + e);
		} finally {
			if(outResponse != null) {
				outResponse.close();
			}
		}
	}
	
	public static void sendJSON(HttpServletResponse response,
			int error, JSONObject content) {
		response.setContentType("application/json");
		response.setCharacterEncoding("utf-8");
		PrintWriter outResponse = null;
		try {
			outResponse = response.getWriter();
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("error", error);
			jsonObject.put("content", content.get("msg"));
			outResponse.print(jsonObject.toString());
			outResponse.flush();
			log.info(jsonObject.toString());
		} catch (IOException e) {
			log.error("json utils exception :" + e);
		} finally {
			if(outResponse != null) {
				outResponse.close();
			}
		}
	}
	
	
	/**
	 * JSONUtils 传输sendJSON的处理
	 * @param response servlet的响应
	 * @param error error = 0 结果为true,error = 1结果为false;
	 * @param message error=1对应的错误信息
	 * @param content error=0对应给request返回的内容
	 */
	public static void sendJSON(HttpServletResponse response,
			int error, JSONArray content) {
		response.setContentType("application/json");
		response.setCharacterEncoding("utf-8");
		PrintWriter outResponse = null;
		try {
			outResponse = response.getWriter();
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("error", error);
			jsonObject.put("content", content);
			outResponse.print(jsonObject.toString());
			outResponse.flush();
			log.info(jsonObject.toString());
		} catch (IOException e) {
			log.error("json utils exception :" + e);
		} finally {
			if(outResponse != null) {
				outResponse.close();
			}
		}
	}
	
	public static void sendJSON(HttpServletResponse response,
			String error, JSONArray countrycontent, JSONArray citycontent) {
		response.setContentType("application/json");
		response.setCharacterEncoding("utf-8");
		PrintWriter outResponse = null;
		try {
			outResponse = response.getWriter();
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("error", error);
			jsonObject.put("countryArr", countrycontent);
			jsonObject.put("cityArr", citycontent);
			outResponse.print(jsonObject.toString());
			outResponse.flush();
		} catch (IOException e) {
			log.error("json utils exception :" + e);
		} finally {
			if(outResponse != null) {
				outResponse.close();
			}
		}
	}
	
	public static void sendJSON(HttpServletResponse response,JSONArray array) {
		response.setContentType("application/json");
		response.setCharacterEncoding("utf-8");
		PrintWriter outResponse = null;
		try {
			outResponse = response.getWriter();
			outResponse.print(array.toString());
			outResponse.flush();
		} catch (IOException e) {
			log.error("json utils exception :" + e);
		} finally {
			if(outResponse != null) {
				outResponse.close();
			}
		}
	}
	
	public static boolean isExits(String key, JSONArray jsonArray, String type) {
		boolean result = false;
		for(int i=0; i< jsonArray.size(); i++) {
			JSONObject json = jsonArray.getJSONObject(i);
			if(json.get("areacode")!= null && json.get("areacode").equals(key) && "area".equalsIgnoreCase(type))
				return true;
			
			if(json.get("citycode")!= null && json.get("citycode").equals(key) && "city".equalsIgnoreCase(type))
				return true;
		}
		return result;
	}
}

 

package com.zte.util;

import java.io.StringWriter;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
/**
 * JSON工具 
 *
 */
public class JSON {
	private static ObjectMapper mapper = new ObjectMapper();
	
	/**
	 * 将实体对象转换成JSON格式的字符串
	 * @param obj
	 * @return
	 */
	public static String toJson(Object obj){
		String json = "";
		try {
			StringWriter writer = new StringWriter();
			JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(writer);
			mapper.writeValue(generator, obj);
			json = writer.toString();
			generator.close();
			writer.close();			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return json;
	}
	
	/**
	 * JSON格式的字符串转成实体对象
	 * @param json
	 * @param valueType
	 * @return
	 */
	public static <T> T fromJson(String json, Class<T> valueType){
		try {
			return null == json ? null : mapper.readValue(json, valueType);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}

 

Map<String, Object> result = new HashMap<String, Object>(2);
try {
			
		} catch (UploadFileException e) {
			result.put("code", 1);
			result.put("msg", e.getMessage());
			writeResponse(response,result);
			return;
		}

private void writeResponse(HttpServletResponse response, Map<String, Object> result) {
		try {
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().write(JSON.toJson(result));
			response.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

 

 另一个JSON工具类:

//Action:
	String s = this.versionService.saveOrUpdateVersion(version);
			if (MDSConstants.SUCCESS.equals(s)) {
				writeJson(new ResultJson(true, getText("保存成功")));
			} else {
				writeJson(new ResultJson(true, getText("保存失败")));
			}			

	success : function(d) {
			var json = $.parseJSON(d);
			if (json.success) {				
				$.messager.show({title : '系统提示',msg :json.msg});				
			}else{
				$.messager.alert('系统提示',json.msg);
			}
		}			
		
或:
	List<MngMmField> fields = this.tableService.getFieldsByTableId(oid,userId);
	if (fields != null && !fields.isEmpty()) {
		writeJosnArray(fields);
	} else {
		writeJosnArray(new ArrayList<MngMmField>());
	}

	<script type="text/javascript">
		// JSON 字符串
		var strJSON = '{"Name":"Tom", "Age":14,"Enable":true}';
		//
		var obj = jQuery.parseJSON(strJSON);
		alert( obj.Name );
	</script>

 

//结果对象ResultJson.java:			
	public class ResultJson  implements Serializable
	{
		  private boolean success = false;
		  private String msg = null;

		  private Integer resultcode = null;
		  private Object result = null;

		  public ResultJson()
		  {
		  }

		  public ResultJson(boolean success)
		  {
			setSuccess(success);
		  }

		  public ResultJson(boolean success, String msg, Object result) {
			setSuccess(success);
			this.msg = msg;
			this.result = result;
		  }

		  public ResultJson(boolean success, String msg) {
			setSuccess(success);
			this.msg = msg;
		  }

		  public ResultJson(boolean success, Object result) {
			setSuccess(success);
			this.result = result;
		  }

		  public String getMsg()
		  {
			return this.msg;
		  }

		  public void setMsg(String msg)
		  {
			this.msg = msg;
		  }

		  public void setResult(Object result)
		  {
			this.result = result;
		  }

		  public Object getResult()
		  {
			return this.result;
		  }

		  public void setSuccess(boolean success)
		  {
			this.success = success;
		  }

		  public boolean isSuccess()
		  {
			return this.success;
		  }

		  public Integer getResultcode()
		  {
			return this.resultcode;
		  }

		  public void setResultcode(Integer resultcode)
		  {
			this.resultcode = resultcode;
		  }
	}

 

//JSON.util
	
	//输出方法
	public void write(String str) {
		try {
			getResponse().setContentType("text/html;charset=utf-8");
			PrintWriter writer = getResponse().getWriter();
			writer.write(str);
			writer.flush();
			writer.close();
		} catch (Exception e) {
			
		}
	}
	
	public void writeJson(Object object, String dataFormatter)
	  {
		if (dataFormatter == null) {
		  dataFormatter = "yyyy-MM-dd";
		}
		String json = JSON.toJSONStringWithDateFormat(object, dataFormatter, new SerializerFeature[0]);
		write(json);
	  }

	public String getJson(Object object, String dataFormatter)
	  {
		if (dataFormatter == null) {
		  dataFormatter = "yyyy-MM-dd";
		}
		return JSON.toJSONStringWithDateFormat(object, dataFormatter, new SerializerFeature[0]);
	  }

	public void writeJson(Object object)
	{
		writeJson(object, null);
	}

	public void writeJsonObject(Object object)
	{
		JSONObject jsonObject = JSONObject.fromObject(object);
		write(jsonObject.toString());
	}

	public void writeJosnArray(Collection collection)
	{
		JSONArray jsonArray = JSONArray.fromObject(collection);
		System.out.println("xxxd+" + jsonArray.toString());
		write(jsonArray.toString());
	}

 

。。。

分享到:
评论
1 楼 握着橄榄枝的人 2013-12-11  
response.setCharacterEncoding("utf-8");  这方法根本就不存在,我在好多地方都看到别人这么写,这是你们自己创的还是写错了。request里面才有这个方法。

相关推荐

    java服务端json工具类

    java服务器用的json工具类,自己封装的,支持beanToJson ListToJson arrayToJson等

    封装完善的json工具类

    将集合、数组、字符串等形式转换成json格式,封装完善的json工具类

    json工具类

    自己写的一个json工具类。

    bean,json工具类

    这个"bean,json工具类"就是为了解决这个问题而设计的,它的主要功能可能包括以下几点: 1. **Bean到JSON转换**:工具类提供了将Java Bean对象转换为JSON字符串的方法。这通常通过使用如Jackson、Gson或Fastjson等...

    asp的JSON工具类

    标题中的"asp的JSON工具类"就是为了解决这一问题,使得在ASP中读取、解析和生成JSON数据变得更加便捷。 JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和...

    Java json工具类,jackson工具类,ObjectMapper工具类

    总结来说,`Java json工具类`如`Jackson`和`ObjectMapper`,以及开发者自定义的`JacksonUtils`工具类,是Java开发中处理JSON数据的关键工具。它们能够方便地将Java对象和JSON格式数据互相转换,同时提供了一系列高级...

    json工具类源代码

    在实际开发中,使用JSON工具类时,常见的操作包括: - **序列化**:将Java对象转换为JSON字符串,这在发送HTTP请求或保存数据到文件时非常有用。 - **反序列化**:将JSON字符串解析为Java对象,便于在程序中使用...

    Json工具类

    本篇将详细介绍`Json工具类`及其相关的知识点。 一、Gson库 Gson是Google提供的一个Java库,能够将Java对象转化为JSON字符串,反之亦然。它通过简单的API设计,使得JSON数据的序列化和反序列化变得非常便捷。例如,...

    JsonUtil json工具类

    JsonUtil json工具类 JsonUtil json工具类

    json工具类,java日期转换,字符串转换等各种工具类

    1. **JSON工具类**: JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。在Java中,我们通常使用`org.json`库或`com.google.gson`库来处理JSON数据。...

    JSON工具类jar包

    Java处理JSON的全套工具类,依赖于以下的JAR包: 1.commons-lang.jar 2.commons-beanutils.jar 3.commons-collections.jar 4.commons-logging.jar 5.ezmorph.jar 6.json-lib-2.2.2-jdk15.jar

    实体类反射非空赋值,AjaxJson工具类

    在“实体类反射非空赋值,AjaxJson工具类”这个主题中,我们将探讨如何使用反射来安全地为实体类的属性赋值,并结合Ajax与JSON进行数据的转换和交互。 首先,让我们深入了解反射的概念。Java反射API提供了Class类,...

    excel 转java 以及JSON工具类

    "Excel转Java以及JSON工具类"提供了一种便捷的方式来管理和转化结构化的数据。这种工具通常用于将Excel表格中的数据转换为Java对象或者JSON格式,方便在编程环境中进行操作和使用。 Excel是一种广泛使用的电子表格...

    XML转JSON工具类

    XML转JSON工具类,支持多层XML嵌套解析转JSON,采用dom4j解析转JSON格式,多次线上环境使用

    JSON工具类包含对象转hashmap

    包含各种对象转换成json对象,还包含把对象中的属性转成hashmap 并且可以过滤为空的或者为null的对象

    JAVA转JSON工具类说明

    java转JSON工具类说明,以后看着函数说明就自己可以随便使用JSON数据了,

    C++学习笔记和实践项目,实践项目包括Json工具类、设计模式的C++实现、消息队列、智能指针,linux下的并发控制工具等

    C++学习笔记和实践项目,实践项目包括Json工具类、设计模式的C++实现、消息队列、智能指针,linux下的并发控制工具、线程池,epoll管理器和Mysql连接池、STL容器的快捷输出工具和页面置换算法(FIFO, LRU, LFU)的...

Global site tag (gtag.js) - Google Analytics