• 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);
        }
    
  • 相关阅读:
    EZOJ #202
    EZOJ #201
    p5156 [USACO18DEC]Sort It Out
    p4363 [九省联考2018]一双木棋chess
    p2150 [NOI2015]寿司晚宴
    p5155 [USACO18DEC]Balance Beam
    p2414 [NOI2011]阿狸的打字机
    实验室断网的解决方案
    人需要看到未来
    门德尔松--罗辑思维
  • 原文地址:https://www.cnblogs.com/format-ch/p/14914029.html
Copyright © 2020-2023  润新知