java-JSON中选定键的掩码值

我有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中,我要遮盖不同的字段.

解决方法:

我认为您应该从日志中排除该字段.以下是使用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);
}
上一篇:改进-java.lang.IllegalStateException:预期为BEGIN_ARRAY,但为BEGIN_OBJECT


下一篇:java-嵌套JSON的POJO格式?