java對象轉(zhuǎn)json字符串蕊程,JsonConfig,忽略指定屬性或忽略空值屬性
1驼唱、demo部分代碼
對象里面是個對象集合list
2辨赐、最終輸出結(jié)果:
3掀序、實現(xiàn)詳細代碼
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sf.json.util.PropertyFilter;
public class IgnoreFieldProcessorImpl implements PropertyFilter {
Logger log = LoggerFactory.getLogger(this.getClass());
/**
* 忽略的屬性名稱
*/
private String[] fields;
/**
* 是否忽略集合
*/
private boolean ignoreColl = false;
/**
* 空參構(gòu)造方法<br/>
* 默認不忽略集合
*/
public IgnoreFieldProcessorImpl() {
// empty
}
/**
* 構(gòu)造方法
* @param fields 忽略屬性名稱數(shù)組
*/
public IgnoreFieldProcessorImpl(String[] fields) {
this.fields = fields;
}
/**
* 構(gòu)造方法
* @param ignoreColl 是否忽略集合
* @param fields 忽略屬性名稱數(shù)組
*/
public IgnoreFieldProcessorImpl(boolean ignoreColl, String[] fields) {
this.fields = fields;
this.ignoreColl = ignoreColl;
}
/**
* 構(gòu)造方法
* @param ignoreColl 是否忽略集合
*/
public IgnoreFieldProcessorImpl(boolean ignoreColl) {
this.ignoreColl = ignoreColl;
}
public boolean apply(Object source, String name, Object value) {
if(source == null || source.getClass() == null){
log.info("====================="+name+","+value);
return true;
}
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) {
//log.error(name+","+value+","+source.getClass().getName());
log.error("沒有找到屬性" + name,e);
}
? ? }
// 忽略集合
if (declaredField != null) {
if(ignoreColl) {
if(declaredField.getType() == Collection.class
|| declaredField.getType() == Set.class) {
return true;
}
}
}
// 忽略設(shè)定的屬性
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;?
? ? }?
public String[] getFields() {
return fields;
}
/**
* 設(shè)置忽略的屬性
* @param fields
*/
public void setFields(String[] fields) {
this.fields = fields;
}
public boolean isIgnoreColl() {
return ignoreColl;
}
/**
* 設(shè)置是否忽略集合類
* @param ignoreColl
*/
public void setIgnoreColl(boolean ignoreColl) {
this.ignoreColl = ignoreColl;
}
}
IgnoreFieldProcessorImpl ?類在傳遞參數(shù)數(shù)組中自定義需要忽略的屬性名,如new String[]{"pwd"}