欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

net.sf.json java对象转json时,忽略值为null的属性,格式化Date对象

程序员文章站 2024-01-21 17:38:58
...
import java.util.Arrays;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.PropertyFilter;

public class JsonUtil {

	public static final String[] ignoreField = new String[] { "orderby", "pageSize", "totalRows", "beginRow" };
	public static final String[] noIgnore = null;

	public static JSONArray toArray(Object obj) {
		return toArray(obj, DateUtil.yyyy_MM_dd1);
	}

	public static JSONObject toObject(Object obj) {
		return toObject(obj, DateUtil.yyyy_MM_dd1);
	}

	public static JSONArray toArray(Object obj, String pattern) {
		return JSONArray.fromObject(obj, JsonUtil.getJsonConfig(pattern, noIgnore));
	}

	public static JSONObject toObject(Object obj, String pattern) {
		return JSONObject.fromObject(obj, JsonUtil.getJsonConfig(pattern, noIgnore));
	}

	public static JSONArray toArray(Object obj, String pattern, String[] ignoreField) {
		return JSONArray.fromObject(obj, JsonUtil.getJsonConfig(pattern, ignoreField));
	}

	public static JSONObject toObject(Object obj, String pattern, String[] ignoreField) {
		return JSONObject.fromObject(obj, JsonUtil.getJsonConfig(pattern, ignoreField));
	}

	public static JsonConfig getJsonConfig(final String pattern, final String[] ignoreField) {
		JsonConfig jc = new JsonConfig();
		JsonValueProcessor jsonValueProcessor = new JsonValueProcessor() {
			public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {
				if (arg1 instanceof java.util.Date) {
					return DateUtil.format((java.util.Date) arg1, pattern);
				}
				return null;
			}

			public Object processArrayValue(Object arg0, JsonConfig arg1) {
				if (arg0 instanceof java.util.Date) {
					return DateUtil.format((java.util.Date) arg0, pattern);
				}
				return null;
			}
		};
		jc.registerJsonValueProcessor(java.util.Date.class, jsonValueProcessor);
		jc.registerJsonValueProcessor(java.sql.Date.class, jsonValueProcessor);
		jc.registerJsonValueProcessor(java.sql.Timestamp.class, jsonValueProcessor);
		PropertyFilter javaPropertyFilter = new PropertyFilter() {
			@Override
			public boolean apply(Object arg0, String arg1, Object arg2) {
				if (!Utils.isEmpty(ignoreField) && Arrays.asList(ignoreField).contains(arg1)) {
					return true;
				}
				if (Utils.isEmpty(arg2)) {
					return true;
				}
				return false;
			}
		};
		jc.setJsonPropertyFilter(javaPropertyFilter);
		return jc;
	}
}

 

相关标签: JavaSE