Gson序列化时排除字段

1.正常序列化

new Gson().toJson(obj)

2.序列化null

Gson gson = new GsonBuilder().serializeNulls().create();
gson.toJson(obj)

3.忽略序列化某字段

  • 排除transient字段
字段加上transient修饰符
public transient int x; 
String json = new Gson().toJson(obj);
  • 排除Modifier为指定类型的字段
Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.PROTECTED).create();
String json = gson.toJson(obj);
  • 使用@Expose注解

没有被@Expose标注的字段会被排除
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(obj);
  • 使用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);
    }
posted @ 2021-09-06 14:02  疯子110  阅读(362)  评论(0编辑  收藏  举报