Java gson replace password value on serialization

How do I replace the password field value with XXX

when de-serializing an object using Gson? I found this post: Gson: How to exclude certain fields from serialization without annotations that mostly skip the field. That would be an option, but I would rather replace the valueXXX

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 was unable to figure out the name of the field. So is there any other option?

I use Gson to register some objects in a "nice" way, so I don't have to worry about formatting when reading the logs.

+1


source to share


2 answers


I feel pretty lame posting this answer. But, this is what you can, it essentially copies and modifies the Java object before serialization.

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")));
    }
}

      



Receives serialization:

{"name":"naishe","password":"xxxxxx"}

      

+2


source


You can skip the cloning step, just serialize it 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;
}

      

+3


source







All Articles