Home > Mobile >  Convert all recursive keys to underscore_with lower_case in java
Convert all recursive keys to underscore_with lower_case in java

Time:06-15

I have json with all key are in camel case inside it list objects. see below my json. My all DTO of property in camel case. scenario is like i am getting camel case json object and the pass this object to third party API. That API is accepting snake with lower case.

Example : knownLanguage to known_language passportNumber to passport_number

{
    "knownLanguage": [
        {
            "language": "Marathi",
            "isWrite": true,
            "isRead": true,
            "isSpeak": true
        },
        {
            "language": "English",
            "isWrite": true,
            "isRead": true,
            "isSpeak": true
        }
    ],
    "internationalInterest": {
        "passportNumber": "1234567898",
        "issueDate": "2020-06-01",
        "expiryDate": "2030-06-01"
    },
    "educationDetails": [
        {
            "education": {
                "degree": "Secondary",
                "boardName": "UP",
                "instituteName": "DAV",
                "startMonth": "June",
                "startYear": "2000",
                "endMonth": "May",
                "endYear": "2001",
                "specialization": "",
                "rollNumber": "",
                "marksType": "CGPA",
                "marks": "",
                "country": "",
                "state": "",
                "district": ""
            }
        },
        {
            "education": {
                "degree": "Bachelors",
                "boardName": "UP",
                "instituteName": "DAV",
                "startMonth": "June",
                "startYear": "2000",
                "endMonth": "May",
                "endYear": "2001",
                "specialization": "",
                "rollNumber": "",
                "marksType": "CGPA",
                "marks": "",
                "country": "",
                "state": "",
                "district": ""
            }
        }
    ],
    "employmentDetails": [
        {
            "employment": {
                "employerName": "No",
                "employmentType": "Permanent",
                "isCurrent": true,
                "jobType": "Full Time",
                "startDate": "2022-06-14",
                "endDate": "2022-06-15",
                "jobRole": "Software Engineer",
                "jobDescription": "",
                "lastDrawnSalary": 10000,
                "country": "India",
                "state": "",
                "district": "No"
            }
        }
    ],
    "disabilityDetails": [
        {
            "disability": {
                "disabilityType": "Blindness",
                "disabilityPercentage": "20"
            }
        }
    ]
}

I want to convert all recursive keys of above json into underscore with lowercase.

output

{
  "known_language": [
    {
      "language": "Hindi",
      "is_write": true,
      "is_read": true,
      "is_speak": true
    },
    {
      "language": "English",
      "is_write": true,
      "is_read": true,
      "is_speak": true
    }
  ],
  "international_interest": {
    "passport_number": "1234567898",
    "issue_date": "2020-06-01",
    "expiry_date": "2030-06-01"
  },
  "education_details": [
    {
      "education": {
        "degree": "Secondary",
        "board_name": "UP",
        "institute_name": "DAV",
        "start_month": "June",
        "start_year": "2000",
        "end_month": "May",
        "end_year": "2001",
        "specialization": "",
        "roll_number": "",
        "marks_type": "CGPA",
        "marks": "",
        "country": "",
        "state": "",
        "district": ""
      }
    },
    {
      "education": {
        "degree": "Bachelors",
        "board_name": "AU",
        "institute_name": "AU",
        "start_month": "June",
        "start_year": "2003",
        "end_month": "May",
        "end_year": "2006",
        "specialization": "Computer",
        "roll_number": "",
        "marks_type": "CGPA",
        "marks": "",
        "country": "",
        "state": "",
        "district": ""
      }
    }
  ],
  "employment_details": [
    {
      "employment": {
        "employer_name": "No",
        "employment_type": "Permanent",
        "is_current": true,
        "job_type": "Full Time",
        "start_date": "2022-06-14",
        "end_date": "2022-06-15",
        "job_role": "Software Engineer",
        "job_description": "",
        "last_drawn_salary": 10000,
        "country": "India",
        "state": "",
        "district": "No"
      }
    }
  ],
  "disability_details": [
    {
      "disability": {
        "disability_type": "Blindness",
        "disability_percentage": "20"
      }
    }
  ]
}

Anyone have have idea how to do it ?

CodePudding user response:

In java 9 you can try using this:

String newJsonString = Pattern.compile("[A-Z](?=(\\w*)\":)")
        .matcher(jsonString)
        .replaceAll(matchResult -> "_"   matchResult.group().toLowerCase());

For lower version you can try this:

    Pattern p = Pattern.compile("[A-Z](?=\\w*\":)");
    Matcher m = p.matcher(jsonString);

    StringBuffer sb = new StringBuffer();
    while(m.find()){
        String match = m.group();
        m.appendReplacement(sb, "_"   match.toLowerCase());
    }
    m.appendTail(sb);
    String newJsonString = sb.toString();

CodePudding user response:

You can use splitByCharacterTypeCamelCase from Apache Commons;

This will return split array, join them using join() from Apache Commons;

private static String getSnakeCaseString(String camelCaseString) {
    String[] split = StringUtils.splitByCharacterTypeCamelCase(camelCaseString);
    String joinedString = StringUtils.join(split, "_");
    return joinedString.toLowerCase();
}

Sample ouput for input "stringToChange":

string_to_change

Use this method for all the keys you want to change.

EDIT ::

String jsonString = "{\n"  
        "    \"degree\": \"Secondary\",\n"  
        "    \"boardName\": \"UP\",\n"  
        "    \"instituteName\": \"DAV\",\n"  
        "    \"startMonth\": \"June\",\n"  
        "    \"startYear\": \"2000\",\n"  
        "    \"endMonth\": \"May\",\n"  
        "    \"endYear\": \"2001\",\n"  
        "    \"specialization\": \"\",\n"  
        "    \"rollNumber\": \"\",\n"  
        "    \"marksType\": \"CGPA\",\n"  
        "    \"marks\": \"\",\n"  
        "    \"country\": \"\",\n"  
        "    \"state\": \"\",\n"  
        "    \"district\": \"\"\n"  
        "}";

JSONObject jsonObject = new JSONObject(jsonString);
JSONObject newJSONObject = new JSONObject();
for (String key : jsonObject.keySet()) {
    String newKey = getSnakeCaseString(key);
    newJSONObject.put(newKey, jsonObject.get(key));
}

System.out.println(newJSONObject);

This is a sample code which changes the key. Handle recursion to change all the keys.

  • Related