Java 替换JSON键中的空白

Java 替换JSON键中的空白,java,json,parsing,Java,Json,Parsing,我正在考虑一个最好的解决方案,用下划线替换JSON键中的所有空格 { "Format": "JSON", "TestData": { "Key with Spaces in it": { "And Again": { "Child_Key1": "Financial", "Child_Key2": null }, ......... ..... 我希望将上述内容转换为如下所示: { "Format

我正在考虑一个最好的解决方案,用下划线替换JSON键中的所有空格

{ 
  "Format": "JSON", 
  "TestData": { 
    "Key with Spaces in it": { 
      "And Again": { 
        "Child_Key1": "Financial", 
        "Child_Key2": null 
      }, 
......... 
..... 
我希望将上述内容转换为如下所示:

{ 
  "Format": "JSON", 
  "TestData": { 
    "Key_with_Spaces_in_it": { 
      "And_Again": { 
        "Child_Key1": "Financial", 
        "Child_Key2": null 
      }, 
......... 
..... 
有什么建议吗


任何Java库都有预定义的函数来执行此操作吗?

您只需读入每个键/值,然后使用
String replace(String oldString,String newString)
方法


更换钥匙

以下代码使用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;
}
简而言之,此方法将遍历整个数组,并用下划线替换任何空格。它是递归的,因此它将深入到子JSONArray中

您可以阅读更多关于JSONArray的信息

如果将数据编码为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);
        }
    }

}
publicstaticvoidremovejsonspaces(jsonobjectthejson){
jObject=newJSONObject(theJSON.trim());
迭代器keys=jObject.keys();
while(keys.hasNext()){
字符串键=(字符串)键。下一步();
if(jObject.get(key)JSONObject实例){
removeJSONSpaces(jObject.get(key))
}否则{
currentEntry=theJSON.getString(i);
fixedEntry=currentEntry.replace(“,”);
currentJSONArray.put(i,fixedEntry);
}
}
}

您可以阅读有关JSONObject的更多信息

仅删除jason代码中字符串上的空格,而不是jason代码中的所有空格

public字符串移除whowspaceinjasonstring(字符串jsonStr){
布尔changeActive=false;
字符串输出=“”;

对于(inti=0;i我使用gson库从json字符串中删除坏键,因为我想创建json的AVRO文件。 Avro不接受带有空格或非字母数字的键,因此我必须先清理输入

上面的代码片段从所有键中删除空格和字符$(迭代)

查看我使用的一个小示例代码

for (String json: allJsons){
        JsonObject schema = new JsonParser().parse(json).getAsJsonObject();
        JsonObject cleanSchema = new JsonObject();
        Set<Map.Entry<String, JsonElement>> entries = schema.entrySet();
        for (Map.Entry<String, JsonElement> entry: entries) {
            String key = entry.getKey().replace("$","").replace(" ","");
            JsonElement value = entry.getValue();
            if (value.isJsonObject()){
                JsonObject subValue = new JsonObject();
                Set <Map.Entry<String, JsonElement>> subEntries = ((JsonObject) value).entrySet();
                for (Map.Entry<String, JsonElement> subEntry: subEntries) {
                    String subKey = subEntry.getKey().replace("$","").replace(" ","");
                    subValue.add(subKey, subEntry.getValue());
                }
                value = subValue;
            }
            cleanSchema.add(key, value);
        }

        System.out.println("Clean schema "+cleanSchema.toString());
        byte[] bytes = converter.convertToAvro(cleanSchema.toString().getBytes(), avroSchema);
        String avroFile = outputFileName+"_"+counter+".avsc";
        Files.write(Paths.get(avroFile), bytes);
        counter++;
        System.out.println("Avro File Created "+avroFile);
    }
for(字符串json:alljson){
JsonObject schema=newJSONParser().parse(json).getAsJsonObject();
JsonObject cleanSchema=新的JsonObject();
Set entries=schema.entrySet();
对于(Map.Entry:entries){
String key=entry.getKey().replace(“$”,”).replace(“,”);
JsonElement value=entry.getValue();
if(value.isJsonObject()){
JsonObject subValue=新的JsonObject();
Set子项=((JsonObject)值).entrySet();
for(Map.Entry子项:子项){
String subKey=subEntry.getKey().replace(“$”,”).replace(“,”);
add(subKey,subEntry.getValue());
}
值=子值;
}
添加(键,值);
}
System.out.println(“cleanSchema”+cleanSchema.toString());
byte[]bytes=converter.convertToAvro(cleanSchema.toString().getBytes(),avroSchema);
字符串avroFile=outputFileName+““+计数器+”.avsc”;
文件.write(路径.get(avroFile),字节);
计数器++;
System.out.println(“创建的Avro文件”+avroFile);
}
试试这个:

      String testJSON = "{\"menu\": {\n" +
        "  \"id no\": \"file\",\n" +
        "  \"value type\": \"File\",\n" +
        "  \"popup value\": {\n" +
        "    \"menu item\": [\n" +
        "      {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},\n" +
        "      {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"},\n" +
        "      {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}\n" +
        "    ]\n" +
        "  }\n" +
        "}}";
             JSONObject json = new JSONObject(testJSON);
             System.out.println("Final output: "+replaceKeyWhiteSpace(json));
将空格替换为“\u1”

private静态JSONObject replaceKeyWhiteSpace(对象json){
JSONObject JSONObject=null;
if(JSONObject的json实例){
jsonObject=(jsonObject)json;
List keyList=newlinkedlist(jsonObject.keySet());
用于(字符串键:键列表){
如果(!key.matches(“.[\\s\t\n]+.*)){
Object value=jsonObject.get(key);
replaceKeyWhiteSpace(值);
继续;
}
对象值=jsonObject.remove(键);
字符串newKey=key.replaceAll(“[\\s\t\n]”,“”);
replaceKeyWhiteSpace(值);
jsonObject.acculate(newKey,value);
}
}else if(JSONArray的json实例){
for(对象:(JSONArray)json){
replaceKeyWhiteSpace(AJA);
}
}
返回jsonObject;

}

这就是我从Json键中删除空白的方法。解决方案适用于JsonArray和JsonObject,只需打印匹配的正则表达式键和空白并替换这些键即可。 现场演示:


我真的很感激你的回答,你的想法看起来不错。但是我想重命名键本身的名称,put()如何重命名键?它会变成一个值吗?我在这里有点困惑。而且这只会替换极端的子键,而不是所有的键:(老兄,还有什么评论吗?你的想法可以在这里触发一个更好的解决方案:)您好,正如我提到的,put不是确切的解决方案。但我已经调整了您的解决方案a,但是。在键和值中,我用SP替换空格,用SYMBOL_关键字替换符号。然后这就解决了我的问题。由于我有一个外部响应映射要做,所以我使用xslt将其替换为实际值,例如,用“”替换SP,类型名为changson 2.8.2
-
JSONArray
中的ged现在是
JSONArray
&
JSONObject
现在是
JSONObject
对于操作JSON字符串,非常不鼓励使用Manuel字符串或常规表达式操作。由于规范,有许多数据、函数格式以及转义字符规则。如果是关于将JSON解析为对象,最好的方法是使用
@JsonProperty(“Key with Spaces in it”)
。有关更多详细信息,请参阅。
      String testJSON = "{\"menu\": {\n" +
        "  \"id no\": \"file\",\n" +
        "  \"value type\": \"File\",\n" +
        "  \"popup value\": {\n" +
        "    \"menu item\": [\n" +
        "      {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},\n" +
        "      {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"},\n" +
        "      {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}\n" +
        "    ]\n" +
        "  }\n" +
        "}}";
             JSONObject json = new JSONObject(testJSON);
             System.out.println("Final output: "+replaceKeyWhiteSpace(json));
private static JSONObject replaceKeyWhiteSpace(Object json) {
JSONObject jsonObject = null;
if (json instanceof JSONObject) {
    jsonObject = (JSONObject) json;
    List<String> keyList = new LinkedList<String>(jsonObject.keySet());
    for (String key : keyList) {
        if (!key.matches(".*[\\s\t\n]+.*")) {
            Object value = jsonObject.get(key);
            replaceKeyWhiteSpace(value);
            continue;
        }

        Object value = jsonObject.remove(key);
        String newKey = key.replaceAll("[\\s\t\n]", "_");

        replaceKeyWhiteSpace(value);

        jsonObject.accumulate(newKey, value);

    }
} else if (json instanceof JSONArray) {
    for (Object aJsonArray : (JSONArray) json) {
        replaceKeyWhiteSpace(aJsonArray);
    }
}
return jsonObject;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class MatcherGroupExample {

    public static void main(String[] args) {

        String text   = "{\"co nf ig\": {\"oauthSecret\": [{\"i d\": 45,\"config123\": {\"oauthSecret\": \"P8n2x5Ht0nFRRB0A\",\"status\": \"CREATED\"},\"SERVER132\": \"1000\"},{\"id\": 46,\"config123\": {\"oauthSecret\": \"wP8n2x5Ht0nFRRB0A\",\"status\": \"CREATED\"},\"SERVER132\": \"1000\"}],\"oauthKey\": \"newtest\",\"SERV ER\": \"1000\"},\"feat ures\": [ 9004, 9005] ,\"d\":\"dd\"}";


        String patternString1 = "\"([^\"]+?[ ]+[^\"]+?)\"\\s*:";

        Pattern pattern = Pattern.compile(patternString1);
        Matcher matcher = pattern.matcher(text);

        while(matcher.find()) {
            System.out.println("found: " + matcher.group(1));
           text= text.replaceAll("\""+matcher.group(1)+"\"","\""+(matcher.group(1).replaceAll(" ",""))+"\"");

        }
         System.out.println("Final output:"+text);
    }
}