问题
How can I replace the value of a password field with XXX while de-serializing an object with Gson? I found this post: Gson: How to exclude specific fields from Serialization without annotations that basically skips the field. This would be an option, but I still would prefer to replace the value with XXX
I also tried this:
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);
}
});
Unfortunately, I wasn't able to determine the name of the field. So is there any other option?
I use Gson to log some objects the "pretty" way, so I don't need to bother with the formatting while reading the logs.
回答1:
I feel pretty lame while posting this answer. But, it's what you can, it essentially copies and changes the Java object, before serializing.
public class User {
private static final Gson gson = new Gson();
public String name;
public String password;
public User(String name, String pwd){
this.name = name;
this.password = pwd;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return new User(this.name, this.password);
}
public static void main(String[] aa){
JsonSerializer<User> ser = new JsonSerializer<User>() {
@Override
public JsonElement serialize(User u, Type t, JsonSerializationContext ctx) {
try {
User clone = (User)u.clone();
clone.password = clone.password.replaceAll(".","x");
return (gson.toJsonTree(clone, User.class));
} catch (CloneNotSupportedException e) {
//do something if you dont liek clone.
}
return gson.toJsonTree(u, User.class);
}
};
Gson g = new GsonBuilder().registerTypeAdapter(User.class, ser).create();
System.out.println(g.toJson(new User("naishe", "S3cr37")));
}
}
Gets serialized to:
{"name":"naishe","password":"xxxxxx"}
回答2:
You can skip the cloning step, just serialize it normally and then replace the password:
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;
}
来源:https://stackoverflow.com/questions/9063558/java-gson-replace-password-value-while-serialization