`
sdfiyon
  • 浏览: 22062 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

Json工具类

    博客分类:
  • J2EE
阅读更多
package cn.fiyo.base.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.bind.ServletRequestDataBinder;

import cn.easecom.platform.module.basic.web.user.UserContext;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonUtils {
	private static final Log log = LogFactory.getLog(JsonUtils.class);
	
	public JsonUtils() {
		
	}
	
	/**
	 * 向客户端输出JSON
	 */
	public static void outputJson(HttpServletResponse response, JSONObject json)
			throws Exception {
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.write(json.toString());
		out.flush();
	}

	/** 
	 * 从一个JSON 对象字符格式中得到一个java对象
	 * 
	 */

	public static Object toBean(String jsonString, Class beanClass) {
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		Object object = JSONObject.toBean(jsonObject, beanClass);
		return object;
	}
	
	public static Object toBean(String jsonString, Class beanClass,Map map) {
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		Object object = JSONObject.toBean(jsonObject, beanClass,map);
		return object;
	}

	/** 
	 * 从json对象集合表达式中得到一个java对象列表
	 * @param jsonString:数组字符串[{key1:value1,key2:value2},{bean2},{bean3},...]
	 * @param pojoClass
	 * @return
	 */
	public static List toList(String jsonString, Class beanClass) {
		JSONArray jsonArray = JSONArray.fromObject(jsonString);
		List list = new ArrayList();
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			Object object = JSONObject.toBean(jsonObject, beanClass);
			list.add(object);
		}
		return list;
	}
	public static List toList(String jsonString, Class beanClass,Map map) {
		JSONArray jsonArray = JSONArray.fromObject(jsonString);
		List list = new ArrayList();
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			Object object = JSONObject.toBean(jsonObject, beanClass,map);
			list.add(object);
		}
		return list;
	}

	/** 
	 * 从json字符串中获取一个map,该map支持嵌套功能
	 * @param jsonString
	 * @return
	 */
	public static Map toMap(String jsonString) {
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		Iterator it = jsonObject.keys();
		Map map = new HashMap();
		while (it.hasNext()) {
			String key = (String) it.next();
			Object value = jsonObject.get(key);
			map.put(key, value);
		}
		return map;
	}
	
	/**
	 * 从json数组中得到相应java数组
	 * @param jsonString
	 * @return
	 */
	public static Object[] toObjectArray(String jsonString) {
		JSONArray jsonArray = JSONArray.fromObject(jsonString);
		return jsonArray.toArray();
	}

	/** 
	 * 从json解析出java字符串数组
	 * @param jsonString
	 * @return
	 */
	public static String[] toStringArray(String jsonString) {
		JSONArray jsonArray = JSONArray.fromObject(jsonString);
		String[] stringArray = new String[jsonArray.size()];
		for (int i = 0; i < jsonArray.size(); i++) {
			stringArray[i] = jsonArray.getString(i);
		}
		return stringArray;
	}

	/** 
	 * 从json解析出javaLong型对象数组
	 * @param jsonString
	 * @return
	 */
	public static Long[] toLongArray(String jsonString) {

		JSONArray jsonArray = JSONArray.fromObject(jsonString);
		Long[] longArray = new Long[jsonArray.size()];
		for (int i = 0; i < jsonArray.size(); i++) {
			longArray[i] = jsonArray.getLong(i);
		}
		return longArray;
	}

	/**
	 * 从json解析出java Integer型对象数组
	 * @param jsonString:[1,2,3,4]
	 * @return
	 */
	public static Integer[] toIntegerArray(String jsonString) {
		JSONArray jsonArray = JSONArray.fromObject(jsonString);
		Integer[] integerArray = new Integer[jsonArray.size()];
		for (int i = 0; i < jsonArray.size(); i++) {
			integerArray[i] = jsonArray.getInt(i);
		}
		return integerArray;
	}

	
	/**
	 * 从json中解析出java Double型对象数组
	 * @param jsonString
	 * @return
	 */
	public static Double[] toDoubleArray(String jsonString) {
		JSONArray jsonArray = JSONArray.fromObject(jsonString);
		Double[] doubleArray = new Double[jsonArray.size()];
		for (int i = 0; i < jsonArray.size(); i++) {
			doubleArray[i] = jsonArray.getDouble(i);
		}
		return doubleArray;
	}

	/**
	 * 将java对象转换成json字符串
	 * @param javaObj
	 * @return
	 */
	public static String toJsonString(Object object) {
		JSONObject json = JSONObject.fromObject(object);
		return json.toString();
	}

	/*
	 * 将java对象转化为json数组字符串
	 * [{"name":"name1","id":"id1"},{"name":"name2","id":"id2"}]
	 */
	public static String toJsonArrayString(List<Object> list) {
		JSONArray jsonArray = JSONArray.fromObject(list);
		return jsonArray.toString();
	}

	private String dateFormat = "yyyy-MM-dd";

    public void setDateFormat(String dateFormat){
        this.dateFormat = dateFormat;
    }

    /**
     * 格式化日期字符串
     */
    public void initBinder(HttpServletRequest request,ServletRequestDataBinder binder){
        SimpleDateFormat dateFormat = new SimpleDateFormat(this.dateFormat);
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
        binder.registerCustomEditor(String.class,new StringTrimmerEditor(false));
    }
   
    @SuppressWarnings("unchecked")
    public static void outputJsonResponse(HttpServletResponse response,boolean result){
    	JSONObject json = new JSONObject();
        json.put("result", result);
        String content=json.toString();
        flushResponse(response,content);
    }
    /*
     * {"result":true,"msg":"abc"}
     */
    @SuppressWarnings("unchecked")
    public static void outputJsonResponse(HttpServletResponse response,boolean result,String message){
    	JSONObject json = new JSONObject();
        json.put("result", result);
        json.put("message", message);
        String content=json.toString();
        flushResponse(response,content);
    }
    @SuppressWarnings("unchecked")
    public static void outputJsonResponse(HttpServletResponse response,boolean result,String message,String userData){
    	JSONObject json = new JSONObject();
        json.put("result", result);
        json.put("message", message);
        json.put("userData", userData);
        String content=json.toString();
        flushResponse(response,content);
    }
    /*
     * {"result":true,"data":{"key1":"value1","key2":"value2"}}
     */
    @SuppressWarnings("unchecked")
    public static void outputJsonResponse(HttpServletResponse response,boolean result,String message,Map userData){
    	JSONObject json = new JSONObject();
        json.put("result", result);
        json.put("message", message);
        if(userData!=null && userData.size()>0)
            json.put("userData", userData);
        String content=json.toString();
        flushResponse(response,content);
    }
    
    /*
     * 输出json数据
     * 输出格式为:{result:true,data:[{"name":"name1","id":"id1"},{"name":"name2","id":"id2"}]}
     */
    public static void outputJsonResponse(HttpServletResponse response,boolean result,List list) {
    	JSONObject json = new JSONObject();
    	json.put("result", result);
        if (list!=null && list.size()>0){
            JSONArray jsonArray = JSONArray.fromObject(list);
            json.put("data", jsonArray);
        }
        String content=json.toString();
        flushResponse(response,content);
    }
       
    /*
     * 输出ext列表的json数据
     * 输出格式为:{totalProperty:12,root:[{"name":"name1","id":"id1"},{"name":"name2","id":"id2"}]}
     */
    public static void outputJsonDataForExt(HttpServletResponse response,int totalProperty,List list) {
    	JSONObject json = new JSONObject();
        json.put("totalProperty", totalProperty);
        if (list!=null && list.size()>0){
            JSONArray jsonArray = JSONArray.fromObject(list);
            json.put("root", jsonArray);
        }
        String content=json.toString();
        flushResponse(response,content);
    }
    /**
     * Method to flush a String as response.
     * @param response
     * @param responseContent
     * @throws IOException
     */
    public static void flushResponse(HttpServletResponse response,String responseContent){
	    response.setCharacterEncoding("UTF-8");
		try {
			PrintWriter writer = response.getWriter();
			writer.write(responseContent);
	        writer.flush();
	        writer.close();
		} catch (IOException e) {
			log.error(e.getMessage());
		}
    }
    /**
     * @param response
     */
    public static void outputXML(HttpServletResponse response, String xml) throws Exception {
        response.setContentType("text/xml; charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(xml);
        out.flush();
    }
    
    /*
     * 属性拷贝
     */
    public void copyProperties(Object dest, Object orig) {
		try {
			BeanUtils.copyProperties(dest, orig);
		} catch (Exception ex) {
			log.error("Copy property error: " + ex.toString());
		}
	}
}

 

这是一个以前项目中用到的JSON类。

分享到:
评论

相关推荐

    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对象,便于在程序中使用...

    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