JSON PII data masking in Java

josh picture josh · Mar 25, 2015 · Viewed 7.3k times · Source

I would like to mask certain elements of JSON and print to logs. Masking can be either by substituting by dummy data or removing the key pair .Is there a utility to do the masking in Java ?

E.g.,

given JSON:

{
    "key1":"value1",
    "key2":"value2",
    "key3":"value3",
}

mask key 2 alone and print JSON:

{
    "key1":"value1",
    "key2":"xxxxxx",
    "key3":"value3",
}

or

{
    "key1":"value1",
    "key3":"value3",
}

Answer

Oleg picture Oleg · Mar 25, 2015

You could use jackson to convert json to map, process map and convert map back to json.

For example:

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

public void mask() throws IOException {
String jsonString = "{\n" +
            "    \"key1\":\"value1\",\n" +
            "    \"key2\":\"value2\",\n" +
            "    \"key3\":\"value3\"\n" +
            "}";
    Map<String, Object> map;    

    // Convert json to map
    ObjectMapper mapper = new ObjectMapper();
    try {
        TypeReference ref = new TypeReference<Map<String, Object>>() { };
        map = mapper.readValue(jsonString, ref);
    } catch (IOException e) {
        System.out.print("cannot create Map from json" + e.getMessage());
        throw e;
    }

    // Process map
    if(map.containsKey("key2")) {
        map.put("key2","xxxxxxxxx");
    }

    // Convert back map to json
    String jsonResult = "";
    try {
        jsonResult = mapper.writeValueAsString(map);
    } catch (IOException e) {
        System.out.print("cannot create json from Map" + e.getMessage());
    }

    System.out.print(jsonResult);