我有一个 ConfigInstance
类,其中包含一个 password
和一个 password_hash
。现在我想使用 gson 序列化对象但排除 password
字段。
public class ConfigInstance {
public String database_address;
public int database_port;
public String database_user;
@Expose(serialize = false)
private String database_pass;
public String database_pass_hash;
public String GetPass() { return database_pass; }
public void Encrypt() { /* Creates the hash before serializing*/ }
public void Decrypt() { /* Creates the password after deserializing */}
}
如您所见,我尝试使用 @Expose(serialize = false)
但它似乎没有任何作用。此外,我已经将该字段设置为私有,因为我认为这将“覆盖” @Expose
但运行以下代码:
private void toFile(File file, ConfigInstance map) {
map.Encrypt();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonConfig = gson.toJson(map);
FileWriter writer;
try {
writer = new FileWriter(file);
writer.write(jsonConfig);
writer.flush();
writer.close();
} catch (IOException e) {
System.out.println("Error exporting config: " + e.toString());
}
}
仍然会导致以下文件内容没有错误:
{
"database_address": "127.0.0.1",
"database_port": 1521,
"database_user": "test",
"database_pass": "test1234",
"database_pass_hash": "B9FE2C011B59F0D0D383D70073E48A19"
}
那我做错了什么?我现在很无能,很感激任何帮助,因为 这 似乎不起作用。
提前致谢。
原文由 ThexBasic 发布,翻译遵循 CC BY-SA 4.0 许可协议
为了获得此结果,您需要使用
@Expose
注释所有字段:并将 Gson 配置为仅公开带注释的字段并忽略其余字段,如下所示:
然后,你会得到:
此外,在反序列化字符串时,您仍将拥有 password 属性。
不过,您仍然可以配置 Gson 序列化 程序来完成此操作。