In the JSON Response String contains auto-added Backslashes

15,827

Solution 1

I know this is an old question, but I got stuck with the same problem , the only difference that, I had a JSONArray instead of a JSONObject . But the method I followed for my problem after scouring Stackoverflow for similar questions was the one I am going to state below, in case anyone comes looking for an answer just as I stumbled across your question.

First of all,you need to study the json response you receive. "{\"name\":\"Name\",\"id\":1}" is a String. You see the " before { and after }. If this string is the raw json you receive from your web service,then your method to escape the backslashes and then building a JSONObject out of that string ought to have worked. One method you could try is :

result = result.trim();
result = result.substring(1,result.length() - 1);
result = result.replace("\\","");

Then,

JSONObject reader = new JSONObject(result);
name = reader.getString("name");
id = reader.getInt("id"); 

The mantra for this solution was to get rid of those extra inverted commas before the json response and then creating a JSONObject from that string.

As for my situation regarding a JSONArray,the solution was as below:

Json response : {"error":false,"myorderdetails":{"order_id":"26","orderjson":"[{\"Name\":\"Disprin\",\"Id\":53,\"Quantity\":1,\"Price\":50}]"}}

JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error)
{
    JSONObject jsonObj= jObj.getJSONObject("myorderdetails");
    String s = jsonObj.getString("orderjson");
    s = s.replace("\\", "");
    JSONArray orderjson = new JSONArray(s);

    for(int i=0;i<orderjson.length();i++){
    JSONObject jsonObject=orderjson.getJSONObject(i);
    String pname = (String)jsonObject.get("Name");
    int pquantity = jsonObject.getInt("Quantity");
    double pprice = jsonObject.getDouble("Price");
}

Solution 2

Adding this header in request solved my problem :

"Content-Type" = "application/x-www-form-urlencoded"
Share:
15,827
Jahanzeb Khan
Author by

Jahanzeb Khan

I am doing BS Computer Science. Its my final year. I have worked on .Net, C#, Java, Sql, Jquery, Javascript, C, Android. I am looking forward to have speciality in .Net and Android both(although both are rivals for me).

Updated on June 22, 2022

Comments

  • Jahanzeb Khan
    Jahanzeb Khan almost 2 years

    I am calling a webservice to get a JSON string response and It contains backslashes which is not in original string. Below is my code for requesting a JSON string object which is: {"name":"Name","id":1}

    protected String doInBackground(String... uri) 
        {
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response;
            String responseString = null;
            try {
                response = httpclient.execute(new HttpGet(uri[0]));
                StatusLine statusLine = response.getStatusLine();
                if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    response.getEntity().writeTo(out);
                    out.close();
                    responseString = out.toString();
                } else{
                    //Closes the connection.
                    response.getEntity().getContent().close();
                    throw new IOException(statusLine.getReasonPhrase());
                }
            } catch (ClientProtocolException e) {
                //TODO Handle problems..
            } catch (IOException e) {
                //TODO Handle problems..
            }
            return responseString;
        }
    

    In post execute I just try to parse this respose string into JSONObject. code is bellow:

    protected void onPostExecute(String result) {
            super.onPostExecute(result);
            TextView t1=(TextView)findViewById(R.id.textView1);
            TextView t2=(TextView)findViewById(R.id.textView2);       
    
            //String s = result.replaceAll("\\", ""); //I have tried to escape backslashes also using this line.
            String name="failure";
            int id;
            try 
            {
                t1.setText(result);
                JSONObject reader = new JSONObject(result.toString()); //Exception on this line.
                //name = reader.getString("name").toString();
                //id = reader.getInt("id");             
                t2.setText(name);
            } 
            catch (Exception e) 
            {
                t2.setText(e.toString());
            }
        }
    

    Rsponse string is: "{\"name\":\"Name\",\"id\":1}" And when I try to parse it to JSONObject it throws an exception says: org.json.JSONException value "{"name":"Name","id":1}" type cannot converted into json object.

    • Panther
      Panther over 9 years
      not sure what is problem, however , backslash does't seem problem. Backslash is just escape characeter. Even in exception string is correctone
    • Jahanzeb Khan
      Jahanzeb Khan over 9 years
      I printed out the information and it prints backslashes...if these are here as escaped characters then it should not be printed?right