6

我正在调用 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;
    }

在执行后我只是尝试将此响应字符串解析为 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 value "{ "name":"Name","id":1}"类型无法转换为 json 对象。

4

3 回答 3

5

我知道这是一个老问题,但我遇到了同样的问题,唯一的区别是,我有一个 JSONArray 而不是 JSONObject 。但是,我在 Stackoverflow 搜索类似问题后所遵循的方法是我将在下面说明的方法,以防有人在我偶然发现你的问题时来寻找答案。

首先,您需要研究您收到的 json 响应。"{\"name\":\"Name\",\"id\":1}"是一个字符串。您会在{之前和之后}看到"是 :

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, \"数量\":1,\"价格\":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");
}
于 2016-04-18T07:47:14.687 回答
1

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

"Content-Type" = "application/x-www-form-urlencoded"
于 2019-09-01T14:01:52.840 回答
0

查看您的列表消息转换器。看起来您的 Json 转换器(例如 MappingJackson2HttpMessageConverter)位于 StringMessageConverter 之前。并且 json 在 '"' 之前添加转义字符 '\' 到它转换的每个字符串。

于 2019-05-29T17:47:29.963 回答