private static void maskList(DocumentContext ctx, String jsonPath, String expression) { ctx.configuration().addOptions(Option.AS_PATH_LIST); Configuration conf = Configuration.builder().options(Option.AS_PATH_LIST).build(); DocumentContext context = JsonPath.using(conf).parse(ctx.jsonString()); List<String> pathList = context.read(jsonPath); /** * when reach here, ctx.read(jsonPath) should only give us a list of strings so that we can replace with MASK_REPLACEMENT_CHAR * list of values can belongs to a same path or different paths, we should treat differently. * two situations: * an array contains multiple String values like: "list": ["ab", "cd", "ef] * or single value belongs to different paths. */ if(pathList != null && pathList.size() == 1) { String path = pathList.get(0); List values = ctx.read(path); JSONArray maskedValue = new JSONArray(); //mask each value in the list of the same path values.forEach(o -> maskedValue.add(replaceWithMask(o.toString(), MASK_REPLACEMENT_CHAR.charAt(0), expression))); ctx.set(path, maskedValue); } else { for (String path : Optional.ofNullable(pathList).orElse(Collections.emptyList())) { Object value = ctx.read(path); ctx.set(path, replaceWithMask(value.toString(), MASK_REPLACEMENT_CHAR.charAt(0), expression)); } } }
private static void maskList(DocumentContext ctx, String jsonPath, String expression) { ctx.configuration().addOptions(Option.AS_PATH_LIST); Configuration conf = Configuration.builder().options(Option.AS_PATH_LIST).build(); DocumentContext context = JsonPath.using(conf).parse(ctx.jsonString()); List<String> pathList = context.read(jsonPath); /** * when reach here, ctx.read(jsonPath) should only give us a list of strings so that we can replace with MASK_REPLACEMENT_CHAR * list of values can belongs to a same path or different paths, we should treat differently. * two situations: * an array contains multiple String values like: "list": ["ab", "cd", "ef] * or single value belongs to different paths. */ if(pathList != null && pathList.size() == 1) { String path = pathList.get(0); List values = ctx.read(path); JSONArray maskedValue = new JSONArray(); //mask each value in the list of the same path values.forEach(o -> maskedValue.add(replaceWithMask(o.toString(), MASK_REPLACEMENT_CHAR.charAt(0), expression))); ctx.set(path, maskedValue); } else { for (String path : Optional.ofNullable(pathList).orElse(Collections.emptyList())) { Object value = ctx.read(path); ctx.set(path, replaceWithMask(value.toString(), MASK_REPLACEMENT_CHAR.charAt(0), expression)); } } }