更换密钥
以下代码使用 Google 的 JSON 解析器来提取密钥,重新格式化它们,然后创建一个新的 JSON 对象:
public static void main(String[] args) {
String testJSON = "{\"TestKey\": \"TEST\", \"Test spaces\": { \"child spaces 1\": \"child value 1\", \"child spaces 2\": \"child value 2\" } }";
Map oldJSONObject = new Gson().fromJson(testJSON, Map.class);
JsonObject newJSONObject = iterateJSON(oldJSONObject);
Gson someGson = new Gson();
String outputJson = someGson.toJson(newJSONObject);
System.out.println(outputJson);
}
private static JsonObject iterateJSON(Map JSONData) {
JsonObject newJSONObject = new JsonObject();
Set jsonKeys = JSONData.keySet();
Iterator<?> keys = jsonKeys.iterator();
while(keys.hasNext()) {
String currentKey = (String) keys.next();
String newKey = currentKey.replaceAll(" ", "_");
if (JSONData.get(currentKey) instanceof Map) {
JsonObject currentValue = iterateJSON((Map) JSONData.get(currentKey));
newJSONObject.add(currentKey, currentValue);
} else {
String currentValue = (String) JSONData.get(currentKey);
newJSONObject.addProperty(newKey, currentValue);
}
}
return newJSONObject;
}
您可以阅读有关 GSON 的更多信息here。
替换值
根据您的 JSON 数据的设置方式,您可能需要将 JSONArray 与 JSONObject 进行切换。
JSONArrays 以 [] 开头和结尾,而 JSONObjects 以 {} 开头和结尾
简而言之,这些方法将遍历整个数组/对象并将所有空格替换为下划线。它们是递归的,因此它们将深入到子 JSONArrays/JSONObjects。
如果 JSON 数据编码为 Java JSONArray,您可以执行以下操作:
public static void removeJSONSpaces(JSONArray theJSON) {
for (int i = 0; while i < theJSON.length(); i++) {
if (theJSON.get(i) instanceof JSONArray) {
currentJSONArray = theJSON.getJSONArray(i);
removeJSONSpaces(currentJSONArray);
} else {
currentEntry = theJSON.getString(i);
fixedEntry = currentEntry.replace(" ", "_");
currentJSONArray.put(i, fixedEntry);
}
}
}
简而言之,此方法将遍历整个数组并将所有空格替换为下划线。它是递归的,所以它会深入到子 JSONArrays。
您可以阅读更多关于 JSONArrays here
如果数据被编码为 JSONObject,您需要执行以下操作:
public static void removeJSONSpaces(JSONObject theJSON) {
jObject = new JSONObject(theJSON.trim());
Iterator<?> keys = jObject.keys();
while(keys.hasNext()) {
String key = (String)keys.next();
if (jObject.get(key) instanceof JSONObject) {
removeJSONSpaces(jObject.get(key))
} else {
currentEntry = theJSON.getString(i);
fixedEntry = currentEntry.replace(" ", "_");
currentJSONArray.put(i, fixedEntry);
}
}
}
您可以阅读更多关于 JSONObjects here