I have a JSON as follows
String str = {'Emp name' : 'JSON','Emp id' : 1,'Salary' : 20997.00}
I want to covert this JSON to XML using java.My java code is here.
JSON json= JSONSerializer.toJSON(str);
XMLSerializer xmlSerializer = new XMLSerializer();
//To Skip the white space from XML data and not from XML Element (By default it does)
xmlSerializer.setSkipWhitespace(true);
//To set type of xml element If it true, it will be type
xmlSerializer.setTypeHintsCompatibility(true);
xmlSerializer.setRootName("book");
String xml = xmlSerializer.write( json );
System.out.println(xml);
I am getting an output if I pass the xml without any space between XML element (i.e Emp name as Empname and Emp id as Empid). I want to remove the whitespace from XML element and not from XML Element content.
解决方案
I decompiled and checked json-lib(2.4) and xom (1.2.5) libraies. Unfortunately there is no such pre/post processors or handlers regarding to key.
This applies both when constructing JSON or building XML as well.
Seems like there is no other way to manually fix keys of JSON. 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();
//To Skip the white space from XML data and not from XML Element (By default it does)
xmlSerializer.setSkipWhitespace(true);
//To set type of xml element If it true, it will be type
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 keyList = new LinkedList(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);
}
}
}
Output is as below:
1
JSON
20997.0
john
wick
albert
smith
hasan
kahraman