import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import java.util.Set;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.PropertyFilter;
public class Test implements PropertyFilter,JsonValueProcessor{
private String format ="yyyy-MM-dd HH:mm:ss";
/**
* 忽略的属性名称
*/
private String[] fields;
/**
* 是否忽略集合
*/
private boolean ignoreColl = false;
public String[] getFields() {
return fields;
}
public void setFields(String[] fields) {
this.fields = fields;
}
public boolean isIgnoreColl() {
return ignoreColl;
}
public void setIgnoreColl(boolean ignoreColl) {
this.ignoreColl = ignoreColl;
}
public Test() {
super();
}
public Test(String format, String[] fields, boolean ignoreColl) {
super();
this.format = format;
this.fields = fields;
this.ignoreColl = ignoreColl;
}
@Override
public boolean apply(Object source, String name, Object value) {
Field declaredField = null;
//忽略值为null的属性
if(value == null)
return true;
//剔除自定义属性,获取属性声明类型
if(!"data".equals(name) && "data"!=name && !"totalSize".equals(name) && "totalSize"!=name ){
try {
declaredField = source.getClass().getDeclaredField(name);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
// 忽略集合
if (declaredField != null) {
if(ignoreColl) {
if(declaredField.getType() == Collection.class
|| declaredField.getType() == Set.class) {
return true;
}
}
}
// 忽略设定的属性
if(fields != null && fields.length > 0) {
if(juge(fields,name)) {
return true;
} else {
return false;
}
}
return false;
}
/**
* 过滤忽略的属性
* @param s
* @param s2
* @return
*/
public boolean juge(String[] s,String s2){
boolean b = false;
for(String sl : s){
if(s2.equals(sl)){
b=true;
}
}
return b;
}
@Override
public Object processArrayValue(Object paramObject,
JsonConfig paramJsonConfig) {
return process(paramObject);
}
@Override
public Object processObjectValue(String paramString, Object paramObject,
JsonConfig paramJsonConfig) {
return process(paramObject);
}
private Object process(Object value){
if(value instanceof Date){
SimpleDateFormat sdf = new SimpleDateFormat(format,Locale.CHINA);
return sdf.format(value);
}
return value == null ? "" : value.toString();
}
public static void main(String[] args) {
JsonConfig config = new JsonConfig();
//设置集合不转换 ---- name过滤不转换
config.setJsonPropertyFilter(new Test("yyyy-MM-dd",new String[]{"name"}, true));
//设置时间转换
config.registerJsonValueProcessor(Date.class,new Test());
Demo demo = new Demo("1", "name", "age", "test", null);
JSONObject object = JSONObject.fromObject(demo, config);
System.out.println(object);
}
}
net.sf.json.JsonConfig整合net.sf.json.util.PropertyFilter
最新推荐文章于 2024-05-13 09:33:13 发布