gson JSON中所选键的掩码值

qyswt5oh  于 2022-11-06  发布在  其他
关注(0)|答案(2)|浏览(199)

我有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中是不同的字段。

baubqpgj

baubqpgj1#

我认为您应该从日志中排除这些字段。下面是一个使用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"}

另一个使用反射的解决方案:

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

px9o7tmv2#

我喜欢上面的解决方案,以屏蔽使用反射,但希望扩展相同的其他字段类型,并保存屏蔽字段再次取消屏蔽。
在字段顶部创建注解@MaskedField
第一个

相关问题