import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonUtils {
public static String toJson(Object object, String... excludedFields) {
GsonBuilder gsonBuilder = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
if (excludedFields != null && excludedFields.length > 0) {
gsonBuilder.addSerializationExclusionStrategy(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes fieldAttributes) {
for (String fieldName : excludedFields) {
if (fieldAttributes.getName().equals(fieldName)) {
return true;
}
}
return false;
}
@Override
public boolean shouldSkipClass(Class<?> aClass) {
return false;
}
});
}
Gson gson = gsonBuilder.create();
return gson.toJson(object);
}
}
使用方式:
// 过滤掉这些字段
String json = JsonUtils.toJson(body, "evalImageList", "invoiceList",
"attachList", "assetList");