从json删除多余的空格

时间:2020-05-01 21:19:53

标签: java json parsing

在Java中,我有一个json字符串,我想从中删除多余的空格。我不想从键和值中的字符中删除空格。

实际JSON字符串

{ "Error" : "Invalid HTTP Method" , "ErrorCode" : "405" , "ErrorDesc" : "Method Not Allowed" } 

必需的JSON

{"Error":"Invalid HTTP Method","ErrorCode":"405","ErrorDesc":"Method Not Allowed"}

6 个答案:

答案 0 :(得分:2)

我会喜欢这样的东西:

public static void main(String[] args) {
    String json = "{ \"Error\": \"Inv\\\"alid HTTP Method\", \"ErrorCode\":\"405\",\"ErrorDesc\":\"Method Not Allowed\"}";

    System.out.println(removeWhitespaces(json));
}

public static String removeWhitespaces(String json) {

    boolean quoted = false;
    boolean escaped = false;
    String out = "";

    for(Character c : json.toCharArray()) {

        if(escaped) {
            out += c;
            escaped = false;
            continue;
        }

        if(c == '"') {
            quoted = !quoted;
        } else if(c == '\\') {
            escaped = true;
        }

        if(c == ' ' &! quoted) {
            continue;
        }

        out += c;

    }

    return out;

}

Testrun返回

{"Error":"Invalid HTTP Method","ErrorCode":"405","ErrorDesc":"Method Not Allowed"}

答案 1 :(得分:2)

更简单,更安全的解决方案是使用 Gson库(只需几行):

public static String simplify(String json) {
    Gson gson = new GsonBuilder().create();

    JsonElement el = JsonParser.parseString(json);
    return gson.toJson(el);
}

,您甚至可以使用Gson的漂亮打印选项撤消整个过程(添加空格):

public static String beautify(String json) {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    JsonElement el = JsonParser.parseString(json);
    return gson.toJson(el);
}

希望这对您有帮助

您可以从此处获取最新版本: Gson Maven Repository

答案 2 :(得分:1)

@Fabian Z所说的内容可能会起作用,但可以进行优化(您无需首先将整个String转换为char数组即可对其进行迭代,并且还应该使用StringBuilder):

public static String removeWhitespaces(String json) {
    boolean quoted = false;

    StringBuilder builder = new StringBuilder();

    int len = json.length();
    for (int i = 0; i < len; i++) {
        char c = json.charAt(i);
        if (c == '\"')
            quoted = !quoted;

        if (quoted || !Character.isWhitespace(c))
            builder.append(c);
    }

    return builder.toString();
}

也在使用时

Character.isWhitespace(c)

它还将删除换行符

答案 3 :(得分:1)

不要忘记转义的引号\"

static String minimize(String input){
     StringBuffer strBuffer = new StringBuffer();    
     boolean qouteOpened = false;
     boolean wasEscaped = false;
     for(int i=0; i<input.length(); i++){
         char c = input.charAt(i);
         if (c == '\\') {
            wasEscaped = true;
         }
         if(c == '"') {
             qouteOpened = wasEscaped ? qouteOpened : !qouteOpened;
         }
         if(!qouteOpened && (c == ' ')){
             continue;
         }
         if (c != '\\') {
            wasEscaped = false;
         }
         strBuffer.append(c);
     }
     return strBuffer.toString();
}

答案 4 :(得分:0)

如果您使用JsonWriter创建该Json代码,则可以这样做

jsonWriter.setIndent("");

删除json代码中的所有空格(已通过Gson的Json Writer测试)

答案 5 :(得分:0)

好吧,这可能是我对这篇文章的最终回答:

public static CharSequence removeWhitespaces(CharSequence json) {
    int len = json.length();

    StringBuilder builder = new StringBuilder(len);

    boolean escaped = false, quoted = false;
    for (int i = 0; i < len; i++) {
        char c = json.charAt(i);
        if (c == '\"') {
            if (!escaped) quoted = !quoted;
            else escaped = false;
        } else if (quoted && c == '\\') {
            escaped = true;
        }

        if (quoted || c != ' ') {
            builder.append(c);
        }
    }

    return builder;
}

或者,如果您要确保摆脱了所有空白字符,请使用:

public static CharSequence removeWhitespaces(CharSequence json) {
    int len = json.length();

    StringBuilder builder = new StringBuilder(len);

    boolean escaped = false, quoted = false;
    for (int i = 0; i < len; i++) {
        char c = json.charAt(i);
        if (c == '\"') {
            if (!escaped) quoted = !quoted;
            else escaped = false;
        } else if (quoted && c == '\\') {
            escaped = true;
        }

        if (quoted || !Character.isWhitespace(c)) {
            builder.append(c);
        }
    }

    return builder;
}

此方法比先将字符串转换为Json结构然后再转换回字符串的效率更高,因为那样会很费时间。

如果输入的字符串很长,则提前告知StringBuilder它应该具有的启动容量也可以大大加快该过程。 (容量不等于长度,这意味着即使您告诉StringBuilder例如它应该具有100的容量,它仍然只会具有您放入其中的文本的长度)

由于StringBuilder实现了CharSequence,因此您可以直接返回整个StringBuilder,而不必将其转换回String。但是,如果您需要String而不是CharSequence,则只需调用builder.toString();即可。在此方法的末尾,将返回类型设置为String。