使用transient
这个方法最简单,给字段加上 transient
修饰符就可以了,如下所示:
1 2 3 4 5 6 7 8 |
class GsonSerialization { public transient int x; // <--- public int y; public GsonSerialization(int x, int y) { this.x = x; this.y = y; } } |
单元测试用例:
1 2 3 4 5 6 |
@Test public void testGsonSerialization() { GsonSerialization obj = new GsonSerialization(1, 2); String json = new Gson().toJson(obj); Assert.assertEquals("{\"y\":2}", json); // <--- } |
使用Modifier指定
这个方法需要用GsonBuilder定制一个GSON实例,如下所示:
1 2 3 4 5 6 7 8 |
class GsonSerialization { protected int x; // <--- public int y; public GsonSerialization(int x, int y) { this.x = x; this.y = y; } } |
单元测试用例:
1 2 3 4 5 6 7 |
@Test public void testGsonSerialization() { Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.PROTECTED).create(); // <--- GsonSerialization obj = new GsonSerialization(1, 2); String json = gson.toJson(obj); // <--- Assert.assertEquals("{\"y\":2}", json); } |
使用@Expose注解
注意,没有被 @Expose 标注的字段会被排除,如下所示:
1 2 3 4 5 6 7 8 9 |
class GsonSerialization { public int x; // <--- @Expose public int y; public GsonSerialization(int x, int y) { this.x = x; this.y = y; } } |
单元测试用例:
1 2 3 4 5 6 7 |
@Test public void testGsonSerialization() { Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); // <--- GsonSerialization obj = new GsonSerialization(1, 2); String json = gson.toJson(obj); // <--- Assert.assertEquals("{\"y\":2}", json); } |
使用ExclusionStrategy定制排除策略
这种方式最灵活,下面的例子把所有以下划线开头的字段全部都排除掉:
1 2 3 4 5 6 7 8 |
class GsonSerialization { public int x; // <--- public int y; public GsonSerialization(int x, int y) { this.x = x; this.y = y; } } |
单元测试用例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
@Test public void testGsonSerialization() { ExclusionStrategy myExclusionStrategy = new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fa){ return fa.getName().startsWith("_"); } @Override public boolean shouldSkipClass(Class<?> clazz){ return false; } }; Gson gson = new GsonBuilder().setExclusionStrategies(myExclusionStrategy).create();// <--- MyObj obj = new MyObj(1, 2); String json = gson.toJson(obj); Assert.assertEquals("{\"y\":2}", json); } |