1. 程式人生 > 其它 >http-快取

http-快取

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);
    }