0

I have a JSONObject which is composed of JSONArrays against some keys.

Here is a sample JSONObject:

Input:

{"UserKey":"DLPAgent","Operation":"DLPRuleMatch","OrganizationId":"2f6cb1a6-ecb8-4578-b680-bf84ded07ff4","IncidentId":"2b2f39ad-84ec-4dce-5800-08d5bee87822","Workload":"OneDrive","SensitiveInfoDetectionIsIncluded":false,"RecordType":11,"Version":1,"UserId":"DLPAgent","CreationTime":"2018-05-21T06:46:18","SharePointMetaData":{"UniqueID":"5710471b-f370-4f0d-be43-f6ba83645137","SiteCollectionGuid":"1692891b-2a42-431e-befa-1da656ce5ec8","SiteCollectionUrl":"https://emumbapk-my.sharepoint.com/personal/qa_emumbapk_onmicrosoft_com","FileName":"Classified.docx","FilePathUrl":"https://emumbapk-my.sharepoint.com/personal/qa_emumbapk_onmicrosoft_com/Documents/Classified.docx","FileOwner":"[email protected]","From":"[email protected]","ItemCreationTime":"2018-04-24T11:40:09","ItemLastModifiedTime":"2018-04-24T11:40:23"},"PolicyDetails":[{"PolicyName":"My policy","Rules":[{"Actions":["NotifyUser"],"RuleId":"61e36207-5ad7-4bc2-94f0-7f8b207e142c","RuleMode":"Enable","ConditionsMatched":{"SensitiveInformation":[{"Confidence":75,"Count":1,"SensitiveType":"a2ce32a8-f935-4bb6-8e96-2a5157672e2c"},{"Confidence":85,"Count":1,"SensitiveType":"e55e2a32-f92d-4985-a35d-a0b269eb687b"},{"Confidence":94,"Count":1,"SensitiveType":"a44669fe-0d48-453d-a9b1-2cc83f2cba77"}]},"Severity":"Low","RuleName":"Low volume of content detected My policy"}],"PolicyId":"82111a23-de2c-418f-b052-67e1ef639100"}],"Id":"73734ce7-fb54-41ab-ec00-08d5bee68e61","UserType":4}

I want to replace all the keys with my own keys retaining the values.

For example I want to replace UserKey with user_key. How can I do this?

With simple JSONObject I was using:

JSONObject.put("my_key" , JSONObject.get("OriginalKey"));

But now I cant use JSONObject.get("OriginalKey") for JSONArray value against a key.

2
  • Do you wish to do that key transformation for all the keys in your input JSONObject ? Commented May 22, 2018 at 10:51
  • @piy26 yes in all keys Commented May 22, 2018 at 10:52

2 Answers 2

1
public class TestMain {
    public static void main(String[] args) throws Exception {
        JSONObject requiredJSONObject = performJSONObject("Your JSONObject");
    }

    public static JSONObject performJSONObject(JSONObject inputObject) throws Exception {
        JSONObject resultObject = new JSONObject();
        Iterator iterator = inputObject.keys();
        while (iterator.hasNext()) {
            String key = (String) iterator.next();
            if (inputObject.get(key) instanceof JSONObject) {
                JSONObject jsonObject = (JSONObject) inputObject.get(key);
                resultObject.put(getModifiedKey(key), performJSONObject(jsonObject));
            } else if (inputObject.get(key) instanceof JSONArray) {
                JSONArray jsonArray = (JSONArray) inputObject.get(key);
                resultObject.put(getModifiedKey(key), performJSONArray(jsonArray));
            } else {
                resultObject.put(getModifiedKey(key), inputObject.get(key));
            }
        }
        return resultObject;
    }

    public static JSONArray performJSONArray(JSONArray inputArray) throws Exception {
        JSONArray resultArray = new JSONArray();
        for (int i = 0; i < inputArray.length(); i++) {
            if (inputArray.get(i) instanceof JSONObject) {
                JSONObject jsonObject = (JSONObject) inputArray.get(i);
                resultArray.put(i, performJSONObject(jsonObject));
            } else if (inputArray.get(i) instanceof JSONArray) {
                JSONArray jsonArray = (JSONArray) inputArray.get(i);
                resultArray.put(i, performJSONArray(jsonArray));
            } else {
                resultArray.put(i, inputArray.get(i));
            }
        }
        return resultArray;
    }

    public static String getModifiedKey(String strn) {
        String[] r = strn.split("(?=\\p{Upper})");
        String result = "";
        for (String str : r)
            result += str.toLowerCase() + "_";
        return result.substring(0, result.length() - 1);
    }
}

Here we need to use recursion, the above solution may helps you. Thanks.

Sign up to request clarification or add additional context in comments.

Comments

0

use the below method to get the modified key

public static String getModifiedKey(String strn) {
            String[] r = strn.split("(?=\\p{Upper})");
            String result = "";
            for (String str : r)
                result += str.toLowerCase() + "_";
            return result.substring(0, result.length()-1);
        }

use below one to insert data

JSONObject.put(getModifiedKey(OriginalKey) , JSONObject.get("OriginalKey"));

3 Comments

It won't change keys of JSONArrays
As per my understanding, you are trying to replace all the keys with your own keys. I have given the method to generate the key. so this is done. Except this what you are trying to perform let me know clearly.
yes I am trying to replace all keys. When I say replace all keys I mean all keys in the JSONObject and JSONArray as well. Your solution would just replace keys in the parent JSONObject. But if I pass a key of JSONArray it will give exception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.