JSON中选定键的掩码值

时间:2015-07-06 09:01:07

标签: java json gson

我有JSON请求和响应,我想在日志中打印JSON,但有一些安全字段我想避免在日志中打印,我试图掩盖字段键: 例如:

掩蔽之前

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

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

我正在使用java Gson lib,请帮我做那个

修改

我想动态传递密钥,所以在函数a中我想屏蔽这些字段,但是在函数b不同的字段中。

1 个答案:

答案 0 :(得分:4)

我认为你应该从日志中排除这些字段。以下是使用Gson@Expose注释的简单示例。

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

输出将是:

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

另一种使用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);
}