繁体   English   中英

从 json 中删除多余的空格

[英]Remove extra white spaces from the json

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

实际 JSON 字符串

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

需要 JSON

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

更简单更安全的解决方案是使用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 存储库

我会用这样的东西 go :

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;

}

试运行返回

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

@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)

它还将删除换行符

不要忘记转义引号\"

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();
}

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

jsonWriter.setIndent("");

删除 json 代码中的所有空格(使用 Gson 的 Json Writer 测试)

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

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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM