Search code examples
javajsongson

Mask value of selected key in JSON


I have JSON request and response, I want to print the JSONs in the log, but there are some secured fields which I want to avoid to print in the log, I am trying to mask fields keys: example:

before masking:

  {"username":"user1","password":"123456","country":"US","creditCardNumber":"1283-1238-0458-3458"}

after masking

{"username":"user1","password":"XXXXXX","country":"US","creditCardNumber":"XXXXXX"}

I am using java Gson lib, please help me to do that

EDIT

I want to pass the keys dynamically, so in function a I want to mask these fields, but in function b different fields.


Solution

  • I think you should exclude that fields from log. Below is a simple example using Gson and @Expose annotation.

    public static void main(String[] args) throws IOException {
        String json = "{\"username\":\"user1\",\"password\":\"123456\",\"country\":\"US\",\"creditCardNumber\":\"1283-1238-0458-3458\"}";
    
        Gson gson = new Gson();
        User user = gson.fromJson(json, User.class);
    
        System.out.println(gson.toJson(user));
    
        Gson gsonExpose = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        System.out.println(gsonExpose.toJson(user));
    }
    
    public class User {
        @Expose
        private String username;
        private String password;
        @Expose
        private String country;
        private String creditCardNumber;
    }
    

    Output will be:

    {"username":"user1","password":"123456","country":"US","creditCardNumber":"1283-1238-0458-3458"}
    {"username":"user1","country":"US"}
    

    Another solution using Reflection:

    public static void main(String[] args) throws IOException {
        String json = "{\"username\":\"user1\",\"password\":\"123456\",\"country\":\"US\",\"creditCardNumber\":\"1283-1238-0458-3458\"}";
    
        Gson gson = new Gson();
        User user = gson.fromJson(json, User.class);
    
        List<String> fieldNames = Arrays.asList("password", "creditCardNumber");
        System.out.println(mask(user, fieldNames, "XXXXXXX"));
    }
    
    public static String mask(Object object, List<String> fieldNames, String mask) {
        Field[] fields = object.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            if (fieldNames.contains(fields[i].getName())) {
                try {
                    fields[i].setAccessible(true);
                    if (fields[i].get(object) != null) {
                        fields[i].set(object, mask);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        Gson gson = new Gson();
    
        return gson.toJson(object);
    }