GSON是Google发布的JSON序列化/反序列化工具,非常容易使用。本文简要讨论在使用GSON将Java对象转成JSON时,如何排除某些字段。
假设有下面这个类:
class MyObj {
public 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("{\"x\":1,\"y\":2}", json);
}
这个方法最简单,给字段加上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); // <---
}
这个方法需要用GsonBuilder定制一个GSON实例,如下所示:
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);
}
注意,没有被@Expose标注的字段会被排除,如下所示:
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);
}
这种方式最灵活,下面的例子把所有以下划线开头的字段全部都排除掉:
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);
}
GSON使用笔记 -- 序列化时排除字段的几种方式,布布扣,bubuko.com
原文:http://blog.csdn.net/zxhoo/article/details/21471005