I decompiled and checked json-lib (2.4) and xom (1.2.5) libraies. Unfortunately, there are no such pre / post processors or handlers in relation to the key. This applies both when building JSON and when creating XML.
There seems to be no other way to manually fix the JSON keys. So please check below snippet:
public static void main(String[] args) {
String str = "{'Emp name' : 'JSON','Emp id' : 1,'Salary' : 20997.00, " +
"'manager' : {'first name':'hasan', 'last name' : 'kahraman'}," +
"'co workers': [{'first name':'john', 'last name' : 'wick'}, " +
"{'first name':'albert', 'last name' : 'smith'}]}";
JsonConfig config = new JsonConfig();
JSON json = JSONSerializer.toJSON(str, config);
fixJsonKey(json);
XMLSerializer xmlSerializer = new XMLSerializer();
xmlSerializer.setSkipWhitespace(true);
xmlSerializer.setTypeHintsCompatibility(true);
xmlSerializer.setRootName("book");
String xml = xmlSerializer.write(json);
System.out.println(xml);
}
private static void fixJsonKey(Object json) {
if (json instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) json;
List<String> keyList = new LinkedList<String>(jsonObject.keySet());
for (String key : keyList) {
if (!key.matches(".*[\\s\t\n]+.*")) {
Object value = jsonObject.get(key);
fixJsonKey(value);
continue;
}
Object value = jsonObject.remove(key);
String newKey = key.replaceAll("[\\s\t\n]", "");
fixJsonKey(value);
jsonObject.accumulate(newKey, value);
}
} else if (json instanceof JSONArray) {
for (Object aJsonArray : (JSONArray) json) {
fixJsonKey(aJsonArray);
}
}
}
The output is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<book>
<Empid type="number">1</Empid>
<Empname type="string">JSON</Empname>
<Salary type="number">20997.0</Salary>
<coworkers class="array">
<e class="object">
<firstname type="string">john</firstname>
<lastname type="string">wick</lastname>
</e>
<e class="object">
<firstname type="string">albert</firstname>
<lastname type="string">smith</lastname>
</e>
</coworkers>
<manager class="object">
<firstname type="string">hasan</firstname>
<lastname type="string">kahraman</lastname>
</manager>
</book>