栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

替换JSON键中的空格

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/438389.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号