替换键
以下代码使用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的更多信息:
这里。
替换值
根据您的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的内容。
如果数据编码为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的更多信息。
@JsonProperty("Key with Spaces in it")
。请参阅https://github.com/FasterXML/jackson-annotations获取更多详细信息。 - wittich