在使用 Gson 反序列化对象时,如何用 XXX
替换密码字段的值?我找到了这篇文章:Gson: How to exclude specific fields from Serialization without annotations基本上跳过了这个领域。这将是一个选项,但我仍然更愿意用 XXX
我也尝试过这个:
GsonBuilder builder = new GsonBuilder().setPrettyPrinting();
builder.registerTypeAdapter(String.class, new JsonSerializer<String>(){
@Override public JsonElement serialize(String value, Type arg1, JsonSerializationContext arg2){
// could not find a way to determine the field name
return new JsonPrimitive(value);
}
});
不幸的是,我无法确定该字段的名称。那么还有其他选择吗?
我使用 Gson 以“漂亮”的方式记录一些对象,所以我在阅读日志时不需要费心格式化。
最佳答案
您可以跳过克隆步骤,只需正常序列化,然后替换密码即可:
public JsonElement serialize(User u, Type t, JsonSerializationContext ctx) {
JsonObject obj = new Gson().toJsonTree(u).getAsJsonObject();
obj.remove("password");
obj.add("password", new JsonPrimitive("xxxxx");
return obj;
}
关于java gson在序列化时替换密码值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9063558/