Skip to content
Advertisement

In Java, how do I mask values of all the matching keys of a JSON, when the structure of JSON isn’t same?

I’m looking for a way to hide/mask the sensitive details of JSON output coming from a response, like account number.

All the answers I got over the web requires me to know the JSON structure before hand. Isn’t there any way to extensively traverse each key and then replace it’s value with required masking character, without knowing the JSON structure beforehand, which means the required key can be within a JSONArray or JSONObject and sometimes within one another.

Advertisement

Answer

Thank you all for the replies, it gave me an insight into the solution I was looking for. However, me and my colleague wrote the exact method we were looking for. The method we wrote accepts a JSON as an JSON Object, the key to be searched and the mask string by which I want the key’s value to be replaced with.

Feel free to contribute on improving the below code.

public static JSONObject maskJSONValue(JSONObject jsonObject, String key, String mask) throws Exception{
    Iterator iterator = jsonObject.keys();
    String localKey = null;
    
    while (iterator.hasNext()){
        localKey = (String) iterator.next();
        if((jsonObject.optJSONArray(localKey) == null) && (jsonObject.optJSONObject(localKey) == null)){
            if((localKey.equals(key))){
                jsonObject.put(localKey, mask);
                return jsonObject;
            }
        }
    }
    if(jsonObject.optJSONObject(localKey) != null)
        maskJSONValue(jsonObject.getJSONObject(localKey), key, mask);

    if(jsonObject.optJSONArray(localKey) != null){
        JSONArray jArray = jsonObject.getJSONArray(localKey);
        for( int i = 0; i < jArray.length(); i++)
            maskJSONValue(jArray.getJSONObject(i), key, mask);
    }

    return jsonObject;
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement