使生效
ExclusionStrategy
喜欢
@RequiredArgsConstructor
public class FieldExclusionStrategy implements ExclusionStrategy {
@NonNull
private final Collection<String> serializedFields;
@Override
public boolean shouldSkipField(FieldAttributes f) {
if(serializedFields.contains(f.getName())) return false;
return true;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) { return false; }
}
使用like
@Test
public void testShouldSkipField() {
Gson gson;
Table table = new Table();
Collection<String> serializedFields = new ArrayList<>();
ArrayList<Table> myTable = new ArrayList<Table>();
myTable.add(new Table("John", "Chicago"));
myTable.add(new Table("David", "Seattle"));
myTable.add(new Table("June", "Dallas"));
serializedFields.add("name");
gson = new GsonBuilder()
.setPrettyPrinting()
.addSerializationExclusionStrategy(
new FieldExclusionStrategy(serializedFields))
.create();
log.info("\n{}", gson.toJson(myTable));
serializedFields.add("location");
gson = new GsonBuilder()
.setPrettyPrinting()
.addSerializationExclusionStrategy(
new FieldExclusionStrategy(serializedFields))
.create();
log.error("\n{}", gson.toJson(myTable));
serializedFields.remove("name");
gson = new GsonBuilder()
.setPrettyPrinting()
.addSerializationExclusionStrategy(
new FieldExclusionStrategy(serializedFields))
.create();
log.error("\n{}", gson.toJson(myTable));
}
上面会记录如下内容
2017-12-23 19:47:17.028信息组织。实例格森。FieldExclutionStrategyTest:37-
[
{
“name”:“John”
},
{
“name”:“David”
},
{
“name”:“June”
}
]
2017-12-23 19:47:17.034错误组织。实例格森。FieldExclutionStrategyTest:44-
[
{
“name”:“John”,
“地点”:“芝加哥”
},
{
“name”:“David”,
“地点”:“西雅图”
},
{
“name”:“June”,
“地点”:“达拉斯”
}
]
2017-12-23 19:47:17.035错误组织。实例格森。FieldExclutionStrategyTest:51-
[
{
“地点”:“芝加哥”
},
{
“地点”:“西雅图”
},
{
“地点”:“达拉斯”
}
]
您需要构建
GSON
再次更改序列化字段名列表后。
GSON公司
第一次调用某个字段名时,在内部缓存结果true | false,并且不会再次查询缓存的字段名。
并添加
排除策略
您需要构建
GSON公司
具有
GsonBuilder
然后注册
排除策略
(或其中许多)。
另请参见
my question
关于此主题。