在 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 的 pretty-print 选项反转整个过程( 添加空格 ):
public static String beautify(String json) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement el = JsonParser.parseString(json);
return gson.toJson(el);
}
希望能帮到你
您可以从这里获得最新版本:
Gson Maven Repository
关于java - 从 json 中删除多余的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61550983/