JSON帮助类

package com.boco.scms.comm;
/***
 * JSON帮助类,对象最多支持3层
 * @author Wanglei
 */
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

public class JSONUtil {

    /**
     * list转JSON
     * @param list
     * @return
     */
	public static String toString(List list) {
		return toString(list, new String());
	}

	/**
	 * @param list
	 * @param filterPropertie 过滤属性名
	 * @return
	 */
	public static String toString(List list, String filterPropertie) {
		return toString(list, new String[] { filterPropertie });
	}

	public static String toString(List list, String[] filterProperties) {
		return JSONArray.fromObject(list, setFilterPropertie(filterProperties))
				.toString();
	}

	/**
	 * 对象转JSON
	 * @param object
	 * @return
	 */
	public static String toString(Object object) {
		return toString(object, new String());
	}

	public static String toString(Object object, String filterPropertie) {
		return toString(object, new String[] { filterPropertie });
	}

	public static String toString(Object object, String[] filterPropertie) {
		return JSONObject.fromObject(object,
				setFilterPropertie(filterPropertie)).toString();
	}

	/**
	 * JSON字符串转List
	 * @param jsonString
	 * @param objectClass 转换后list包含类
	 * @return
	 */
	public static List toBean(String jsonString, Class objectClass) {
		return toBean(jsonString, objectClass, null);
	}

	public static List toBean(String jsonString, Class objectClass,
			String filterPropertie) {
		JSONArray array = JSONArray.fromObject(jsonString,
				setFilterPropertie(filterPropertie));
		return (List) JSONArray.toCollection(array, objectClass);
	}

	/**
	 * 过滤器
	 * @param filterPropertie
	 * @return
	 */
	public static JsonConfig setFilterPropertie(final String filterPropertie) {
		String[] str = new String[] { filterPropertie };
		return setFilterPropertie(str);
	}

	public static JsonConfig setFilterPropertie(final String[] filterProperties) {
		JsonConfig config = new JsonConfig();
		config.setJsonPropertyFilter(new PropertyFilter() {
			public boolean apply(Object source, String name, Object value) {
				boolean bool = false;
				for (int i = 0; i < filterProperties.length; i++) {
					if (name.equals(filterProperties[i])) {
						bool = true;
						break;
					}
				}
				return bool;
			}
		});
		return config;
	}

}

你可能感兴趣的:(ext)