2

I am trying to rename key names in a json object.I can rename at the top level, but unable to rename if the key present inside another object or if it present in a List Object.

This is what i have tried so far.

         try {
                jsonObject.put(value, jsonObject.remove(key));
                LOG.trace("Renaming Field {} with Field {}", key, value);
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }

Here is an Example Object.

 {
      "id": 123,
      "contactInformation": {
        "contact": {
          "email": "[email protected]",
        }
      },
      "supportingCustomer": [
        {
          "supportingCustomerName": "JOHN"
        },
        {
          "supportingCustomerName": "JOHN"
        }

      ]

}

Here I can rename Id, but having difficulty renaming supportingCustomerName and also contactInformation.contact.email using org.json.JSONObject ? Or is there any other library, i can use to rename keys.Any Help would be appreciated?

My JSON And key are dynamic not fixated.

6
  • You can use a regex to replace the keys. Commented Jul 6, 2022 at 17:18
  • @AliasCartellano I can rename high level fields.But How Can i Do it for nested and keys inside List? Commented Jul 6, 2022 at 17:23
  • You can replace keys using str = str.replace("supportingCustomerName","Example"); System.out.println(str); on the string of the jsonObject. Commented Jul 6, 2022 at 17:36
  • What if the another nested object have same name and i don't want to replace that field?Which will not be idea.I would like to only change key which is referred by the client Commented Jul 6, 2022 at 17:38
  • 1
    Try iterating through the JSON and renaming the keys that match the values to change. Commented Jul 6, 2022 at 17:48

1 Answer 1

0

Finally Ended Up using

 implementation group: 'com.jayway.jsonpath', name: 'json-path', version: '2.7.0' 


@Override
public DocumentContext renameKey(JsonPath path, String oldKeyName, String newKeyName) {
  List<String> modified =  path.renameKey(json, oldKeyName, newKeyName, configuration.addOptions(Option.AS_PATH_LIST));
  if(logger.isDebugEnabled()){
    for (String p : modified) {
      logger.debug("Rename path {} new value {}", p, newKeyName);
    }
  }
  return this;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain this function please?
Basically you convert json to jsonpath ,get the path and rename the keys in position based. For example $ is your root, and $.id is first id and $contactInformation. contact is another path like that.

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.