我反编译并检查了json-lib(2.4)和xom(1.2.5)的图书馆.不幸的是,没有关于密钥的这样的前/后处理器或处理程序.
这既适用于构造JSON,也适用于构建XML.
似乎没有其他方法可以手动修复JSON的密钥.所以请查看下面的代码:
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);
}
}
}
输出如下:
1
JSON
20997.0
john
wick
albert
smith
hasan
kahraman