从字符串中删除所有出现的\

Swa*_*yam 20 java regex string replace escaping

我正在尝试使用JSON从服务器获取一组对象.

服务器向我发送以下字符串.

"[{\"DealComment\":null,\"DealVotes\":[],\"DealId\":1,\"CompanyId\":1,\"StartDate\":\"2012-12-13T00:00:00\",\"EndDate\":\"2012-12-16T00:00:00\",\"CouponCode\":\"Test Coupon 1\",\"Description\":\"Test Deal Description 1\",\"VoteUp\":null,\"VoteDown\":null,\"ViewCount\":null,\"Title\":\"Test Deal 1\"},{\"DealComment\":null,\"DealVotes\":[],\"DealId\":2,\"CompanyId\":1,\"StartDate\":\"2012-12-16T00:00:00\",\"EndDate\":\"2012-12-17T00:00:00\",\"CouponCode\":\"Test Coupon 2\",\"Description\":\"Test Description 2\",\"VoteUp\":null,\"VoteDown\":null,\"ViewCount\":null,\"Title\":\"Test Deal 2\"},{\"DealComment\":null,\"DealVotes\":[],\"DealId\":3,\"CompanyId\":1,\"StartDate\":\"2012-12-14T00:00:00\",\"EndDate\":\"2012-12-15T00:00:00\",\"CouponCode\":\"Test Code 3\",\"Description\":\"Test Description 3\",\"VoteUp\":null,\"VoteDown\":null,\"ViewCount\":null,\"Title\":\"Test Deal 3\"},{\"DealComment\":null,\"DealVotes\":[],\"DealId\":4,\"CompanyId\":1,\"StartDate\":\"2012-12-12T00:00:00\",\"EndDate\":\"2012-12-13T00:00:00\",\"CouponCode\":\"Test Coupon 4\",\"Description\":\"Test Description 4\",\"VoteUp\":null,\"VoteDown\":null,\"ViewCount\":null,\"Title\":\"Test Deal 4\"},{\"DealComment\":null,\"DealVotes\":[],\"DealId\":5,\"CompanyId\":2,\"StartDate\":\"2012-12-12T00:00:00\",\"EndDate\":\"2012-12-14T00:00:00\",\"CouponCode\":\"AwD\",\"Description\":\"Very awesome deal!\",\"VoteUp\":null,\"VoteDown\":null,\"ViewCount\":null,\"Title\":\"Awesome Deal 1\"}]"
Run Code Online (Sandbox Code Playgroud)

现在,如果你仔细查看字符串,你会发现它包含一个\"而不是每一个".该字符串现在无法格式化为JSONArray.所以,我需要更换的每个实例\"",这将有一个非常简单的任务,也\没有一个转义序列.

我尝试使用以下代码.

String jsonFormattedString = jsonStr.replaceAll("\\", "");
Run Code Online (Sandbox Code Playgroud)

但它给了我以下例外.

12-19 00:35:59.575: W/System.err(444): java.util.regex.PatternSyntaxException: Syntax error U_REGEX_BAD_ESCAPE_SEQUENCE near index 1:
12-19 00:35:59.575: W/System.err(444): \
12-19 00:35:59.575: W/System.err(444):  ^
Run Code Online (Sandbox Code Playgroud)

我的整个代码,如果有任何用处:

public void getAllDealsFromServerJson()
{

    String apiUrl = "http://passme.azurewebsites.net/api/TestApi/";


    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
    HttpResponse response;
    JSONObject json = new JSONObject();

    try{
        HttpPost httpPost = new HttpPost(apiUrl);
        json.put("requestType", "getalldeals" );

        StringEntity se = new StringEntity( json.toString());  
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httpPost.setEntity(se);
        response = client.execute(httpPost);
        Log.d("Http Response:", response.toString());
        jsonResponse = response.toString();

        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String jsonStr = reader.readLine();
        Log.d("String Response", jsonStr);
        String jsonFormattedString = jsonStr.replaceAll("\\", ""); // gives error
        Log.d("Formatted String", jsonFormattedString);
        //JSONTokener tokener = new JSONTokener(jsonFormattedString);
        /*JSONObject finalResult = new JSONObject(tokener);
        Log.d("JSON Response", "" + finalResult.optString("Title"));*/
        JSONArray resultArray = new JSONArray(jsonFormattedString);
        Log.d("JSON Array Result Length", "" + resultArray.length());
        Log.d("JSON Array Result ", "" + resultArray.getJSONObject(0).optInt("DealId"));

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

Ósc*_*pez 32

试试这个:

String jsonFormattedString = jsonStr.replaceAll("\\\\", "");
Run Code Online (Sandbox Code Playgroud)

因为反斜杠是正则表达式中的转义字符(replaceAll()接收一个作为参数),所以它也必须被转义.

  • 这可以解决手头的问题,但它可能会导致问题.这里我们假设反斜杠的唯一用法是为双引号添加前缀,这对于_this_示例数据可能是正确的.根本原因是服务器是对数据进行双重JSON编码.如果没有专门解决这个问题,你的代码就有一个隐藏的bug,只有当最终结果有一个真正的反斜杠被意外删除时才会爆炸. (8认同)
  • `String jsonFormattedString = jsonStr.replace('\\','');`因为没有双重转义而更容易.文档说:返回一个新字符串,该字符串是用newChar替换此字符串中所有出现的oldChar. (3认同)
  • @HunterMcMillen:不太好.OP使用`replaceAll(String,String)`,而@mikejones建议使用`replace(char,char)`.(不幸的是,@ mikejones的解决方案也没有用,因为没有"空字符"````. (3认同)
  • 惊人的!像魅力一样工作!非常感谢先生! (2认同)

Krz*_*soń 14

实际上正确的方法是:

String jsonFormattedString = jsonStr.replace("\\\"", "\"");
Run Code Online (Sandbox Code Playgroud)

要替换只\"",不是所有\什么(它会吃了你的斜线以JSON字符串,如果你的).与流行的相反相反replace(...)也取代了所有出现的给定字符串,就像replaceAll(...)它只是不使用正则表达式所以它通常更快.


Ale*_*nko 9

只需使用:

try {
        jsonFormattedString = new JSONTokener(jsonString).nextValue().toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

查看文档

  • 这将是正确的做法,而不是使用正则表达式或字符串替换 \\。 (4认同)
  • 这应该是正确的答案,通过替换方法,JSON 中可能会出现一些其他格式问题。 (2认同)

d.r*_*aev 6

你可以只使用:

str.replace("\\","");
Run Code Online (Sandbox Code Playgroud)

Replace 采用字符串作为参数,replaceAll 使用 RegEx。它也可能像这样工作:

str.replaceAll("\\\\", "");
Run Code Online (Sandbox Code Playgroud)


jim*_*mbo 5

看起来你的传入字符串是双重JSON编码.你应该解码它,然后再解码.

以下是我在Java中如何做到这一点的最佳猜测:

JSONArray resultArray = new JSONArray(new JSONString(jsonFormattedString));
Run Code Online (Sandbox Code Playgroud)

我假设这JSONString是一种类型.您的实际解决方案可能有所

在正常情况下,我希望服务能够直接为您提供JSON.看来这个服务给你一个包含 JSON 的字符串(根据JSON规范编码).

这是以下之间的区别:

String someJSON = "[0, 1, 2]";
String doublyEncodedJSON = "\"[0, 1, 2]\"";
Run Code Online (Sandbox Code Playgroud)

注意额外的前导和尾随引号?那是因为后者是一串JSON.你必须解码它两次以获得实际的对象.