在JSON响应字符串中包含了自动添加的反斜杠

8
我正在调用一个Web服务以获取JSON字符串响应,但它包含了不在原始字符串中的反斜杠。下面是我请求JSON字符串对象的代码:{"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;
    }

在post execute中,我只是尝试将这个响应字符串解析为JSONObject。代码如下:

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

响应字符串为:"{\"name\":\"Name\",\"id\":1}",当我尝试将其解析为JSONObject时,会抛出异常,提示org.json.JSONException值"{"name":"Name","id":1}"类型无法转换为json对象。


不确定问题出在哪里,但是反斜杠似乎不是问题。反斜杠只是转义字符。即使在异常字符串中也是正确的。 - Panther
我打印出了信息,但它会打印反斜杠...如果这些是转义字符,则不应该打印,对吧? - Jahanzeb Khan
3个回答

6

我知道这是一个老问题,但我遇到了同样的问题,唯一的区别是我有一个JSONArray而不是JSONObject。但是,在Stackoverflow上搜寻类似问题后,我遵循的解决方法是下面我将要阐述的方法,以防有人像我一样偶然发现你的问题并寻找答案。

首先,您需要研究您收到的JSON响应。 "{\"name\":\"Name\",\"id\":1}" 是一个字符串。您可以在{之前和之后看到"。如果这个字符串是您从Web服务接收到的原始JSON,则您的方法应该逃脱反斜杠,然后构建一个JSONObject。您可以尝试的一种方法是:

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

那么,

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

这个解决方案的口号是:去掉json响应之前那些额外的引号,然后从该字符串创建一个JSONObject。
至于我在JSONArray方面的情况,解决方法如下:
Json响应:{"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");
}

2

在请求中添加此标头解决了我的问题:

"Content-Type" = "application/x-www-form-urlencoded"

0

查看您的消息转换器列表。看起来您的Json转换器(例如MappingJackson2HttpMessageConverter)位于StringMessageConverter之前。而且JSON会在将每个字符串转换为JSON时,在双引号前添加转义字符 '\'。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接