Skip to content

Instantly share code, notes, and snippets.

@baldawar
Created October 9, 2023 20:13
Show Gist options
  • Save baldawar/e7d12330cb3214055a287fda22ebfddb to your computer and use it in GitHub Desktop.
Save baldawar/e7d12330cb3214055a287fda22ebfddb to your computer and use it in GitHub Desktop.
Anonymize JSON in Java using JacksonMapper
package software.amazon.event.ruler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
public class AnonymizeJSON {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final Map<String, String> keyToValue = new HashMap<>();
public static void anonymizeJson(String json) throws JsonProcessingException {
final JsonNode jsonNode = OBJECT_MAPPER.readTree(json);
traverseNode(jsonNode, (x) -> {
if (!keyToValue.containsKey(x)) {
keyToValue.put(x, generateRandomAlphabeticString(x.length()));
}
return keyToValue.get(x);
});
System.out.println("\n------------------------------");
System.out.println(OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode));
System.out.println("\n------------------------------");
}
private static void traverseNode(JsonNode node, Function<String, String> replaceFunc) {
if(node.isObject()) {
ObjectNode objectNode = (ObjectNode) node;
final Iterator<Map.Entry<String, JsonNode>> fields = objectNode.fields();
while(fields.hasNext()) {
final Map.Entry<String, JsonNode> next = fields.next();
final JsonNode childNode = next.getValue();
if(childNode.isTextual()) {
objectNode.put(next.getKey(), replaceFunc.apply(childNode.asText()));
} else {
traverseNode(childNode, replaceFunc);
}
}
} else if(node.isArray()) {
ArrayNode arrayNode = (ArrayNode) node;
for(int i=0; i< arrayNode.size(); i++) {
final JsonNode childNode = arrayNode.get(i);
if(childNode.isTextual()) {
arrayNode.set(i, replaceFunc.apply(childNode.asText()));
} else {
traverseNode(childNode, replaceFunc);
}
}
}
}
private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public static String generateRandomAlphabeticString(int length) {
StringBuilder randomString = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int randomIndex = ThreadLocalRandom.current().nextInt(ALPHABET.length());
char randomChar = ALPHABET.charAt(randomIndex);
randomString.append(randomChar);
}
return randomString.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment