GSON序列化时排除字段的几种方式


使用transient


这个方法最简单,给字段加上 transient 修饰符就可以了,如下所示:

class GsonSerialization {
    public transient int x; // <---
    public int y;
    public GsonSerialization(int x, int y) {   
        this.x = x;   
        this.y = y;  
    }   
}

单元测试用例:

@Test 
public void testGsonSerialization() {
	GsonSerialization obj = new GsonSerialization(1, 2);
	String json = new Gson().toJson(obj);
	Assert.assertEquals("{\"y\":2}", json); // <--- 
}

使用Modifier指定


这个方法需要用GsonBuilder定制一个GSON实例,如下所示:

class GsonSerialization {
	protected int x; // <---
	public int y;
	public GsonSerialization(int x, int y) {   
		this.x = x;   
		this.y = y;  
	}   
}

单元测试用例:

@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 标注的字段会被排除,如下所示:

class GsonSerialization {
	public int x; // <---
	@Expose
	public int y;
	public GsonSerialization(int x, int y) {   
		this.x = x;   
		this.y = y;  
	}   
}

单元测试用例:

@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定制排除策略


这种方式最灵活,下面的例子把所有以下划线开头的字段全部都排除掉:

class GsonSerialization {
	public int x; // <---
	public int y;
	public GsonSerialization(int x, int y) {   
		this.x = x;   
		this.y = y;  
	}   
}

单元测试用例:

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

参考链接


GSON序列化时排除字段的几种方式

发布者

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注