替换JSON键中的空格

替换JSON键中的空格,第1张

替换JSON键中的空格

更换钥匙

以下代码使用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数据的设置方式,您可能需要使用JSONObject切换JSONArray。

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的更多信息



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5133289.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-17
下一篇2022-11-17

发表评论

登录后才能评论

评论列表(0条)

    保存