JSON PII data masking in Java

断了今生、忘了曾经 提交于 2019-12-12 04:54:53

问题


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",
}

回答1:


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


来源:https://stackoverflow.com/questions/29263036/json-pii-data-masking-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!