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

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;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值