GSON是Google發(fā)布的JSON序列化/反序列化工具,非常容易使用。本文簡(jiǎn)要討論在使用GSON將Java對(duì)象轉(zhuǎn)成JSON時(shí),如何排除某些字段。
最簡(jiǎn)單的用法
假設(shè)有下面這個(gè)類:
- class MyObj {
-
- public int x;
- public int y;
-
- public MyObj(int x, int y) {
- this.x = x;
- this.y = y;
- }
-
- }
最簡(jiǎn)單的GSON用法如下所示:
- @Test
- public void gson() {
- MyObj obj = new MyObj(1, 2);
- String json = new Gson().toJson(obj);
- Assert.assertEquals("{\"x\":1,\"y\":2}", json);
- }
方法1:排除null字段
null字段,默認(rèn)就不會(huì)序列化的,如下所示:
- class MyObj {
-
- private int intField;
- private String strField;
-
- }
- @Test
- public void gson() {
- MyObj obj = new MyObj();
- Assert.assertEquals("{\"intField\":0}", new Gson().toJson(obj));
- }
要想序列化null字段,需要顯示的進(jìn)行設(shè)置:
- @Test
- public void serializeNulls() {
- MyObj obj = new MyObj();
- Gson gson = new GsonBuilder().serializeNulls().create();
- Assert.assertEquals("{\"intField\":0,\"strField\":null}", gson.toJson(obj));
- }
方法2:排除transient字段
這個(gè)方法最簡(jiǎn)單,給字段加上transient修飾符就可以了,如下所示:
- class MyObj {
-
- public transient int x; // <---
- public int y;
-
- public MyObj(int x, int y) {
- this.x = x;
- this.y = y;
- }
-
- }
- @Test
- public void gson() {
- MyObj obj = new MyObj(1, 2);
- String json = new Gson().toJson(obj);
- Assert.assertEquals("{\"y\":2}", json); // <---
- }
方法3:排除Modifier為指定類型的字段
這個(gè)方法需要用GsonBuilder定制一個(gè)GSON實(shí)例,如下所示:
- class MyObj {
-
- protected int x; // <---
- public int y;
-
- public MyObj(int x, int y) {
- this.x = x;
- this.y = y;
- }
-
- }
- @Test
- public void gson() {
- Gson gson = new GsonBuilder()
- .excludeFieldsWithModifiers(Modifier.PROTECTED) // <---
- .create();
-
- MyObj obj = new MyObj(1, 2);
- String json = gson.toJson(obj); // <---
- Assert.assertEquals("{\"y\":2}", json);
- }
方法4:使用@Expose注解
注意,沒有被@Expose標(biāo)注的字段會(huì)被排除,如下所示:
- class MyObj {
-
- public int x;
- @Expose public int y; // <---
-
- public MyObj(int x, int y) {
- this.x = x;
- this.y = y;
- }
-
- }
- @Test
- public void gson() {
- Gson gson = new GsonBuilder()
- .excludeFieldsWithoutExposeAnnotation() // <---
- .create();
-
- MyObj obj = new MyObj(1, 2);
- String json = gson.toJson(obj);
- Assert.assertEquals("{\"y\":2}", json);
- }
方法5:使用ExclusionStrategy定制字段排除策略
這種方式最靈活,下面的例子把所有以下劃線開頭的字段全部都排除掉:
- class MyObj {
-
- public int _x; // <---
- public int y;
-
- public MyObj(int x, int y) {
- this._x = x;
- this.y = y;
- }
-
- }
- @Test
- public void gson() {
- 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);
- }
|