Gson实现JSON字段过滤
程序员文章站
2024-03-16 09:27:40
...
依赖jar:
<properties>
<gson.version>2.3.1</gson.version>
</properties>
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
</dependencies>
实现代码:
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonRenderer {
/**
* 将 Bean 转换为 JSON
* @author
* @param Bean 实体
* @param 需要转换的字段
* @return JSON 字符串
*/
public static String toJson(Object bean, final String [] filter){
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setExclusionStrategies(new ExclusionStrategy() {
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
public boolean shouldSkipField(FieldAttributes f) {
for (final String v : filter) {
if(f.getName().equals(v))
return false;
}
return true;
}
});
gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss");
Gson gson = gsonBuilder.create();
return gson.toJson(bean);
}
}
下一篇: 简单查找算法