Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all occurrences of \ from string

I am trying to get an array of objects from the server, using JSON.

The server sends me the following string.

"[{\"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\"}]"

Now, if you look at the string closely, you would notice that it contains an \" instead of every ". The string cannot be formatted to a JSONArray right now. So, I need to replace every occurrence of \" with " , which would have a pretty easy task, had \ not been an escape sequence.

I tried using the following code.

String jsonFormattedString = jsonStr.replaceAll("\\", "");

But it gives me the following exception.

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):  ^

My whole code, in case it is of any use :

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();
    }
}
like image 397
Swayam Avatar asked Sep 06 '25 13:09

Swayam


2 Answers

Try this:

String jsonFormattedString = jsonStr.replaceAll("\\\\", "");

Because the backslash is the escaping character in a regular expression (replaceAll() receives one as parameter), it has to be escaped, too.

like image 186
Óscar López Avatar answered Sep 09 '25 17:09

Óscar López


Actually the correct way would be:

String jsonFormattedString = jsonStr.replace("\\\"", "\"");

You want to replace only \" with ", not all \ with nothing (it would eat up your slashes in json strings, if you have ones). Contrary to popular believe replace(...) also replaces all occurrences of given string, just like replaceAll(...), it just doesn't use regexp so it usually be faster.

like image 37
Krzysztof Krasoń Avatar answered Sep 09 '25 16:09

Krzysztof Krasoń