6

JSON 文字列応答を取得するために Web サービスを呼び出していますが、元の文字列にはないバックスラッシュが含まれています。以下は、 {"name":"Name","id":1}である JSON 文字列オブジェクトを要求するための私のコードです。

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

Rsponse 文字列は次のとおりです: "{\"name\":\"Name\",\"id\":1}" そして、それを JSONObject に解析しようとすると、次のような例外がスローされます: org.json.JSONException 値 "{ "name":"Name","id":1}"型は json オブジェクトに変換できません。

4

3 に答える 3

5

これは古い質問であることは知っていますが、同じ問題に行き詰まりました。唯一の違いは、 JSONObject の代わりに JSONArray があったことです。しかし、同様の質問についてStackoverflowを精査した後、私が問題に対して従った方法は、あなたの質問に出くわしたのと同じように誰かが答えを探しに来た場合に備えて、以下に述べる方法でした.

まず、受け取った json レスポンスを調べる必要があります。"{\"name\":\"Name\",\"id\":1}"は文字列です。" before { and after }が表示されますこの文字列が Web サービスから受け取った生の json である場合、バックスラッシュをエスケープし、その文字列から JSONObject を構築する方法は機能しているはずです。試すことができる方法の 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 に答える