Google Gson 支持基于 Java 访问修饰符过滤字段,包括:
public / default / protected / private / static / final
- 1
示例
(1) POJO 类
class GsonObject {
public String publicField = "PUBLIC";
String defaultField = "DEFAULT";
protected String protectedField = "PROTECTED";
private String privateField = "PRIVATE";
static String staticField = "STATIC";
final String finalField = "FINAL";
}
(2) 测试代码
@Test
public void test() throws IOException {
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(
java.lang.reflect.Modifier.PRIVATE,
java.lang.reflect.Modifier.STATIC)
.create();
System.out.println(gson.toJson(new GsonObject()));
}
运行结果: