如何将字符串转换为JSON对象?

时间:2016-03-11 07:29:31

标签: java android json deserialization

我正在使用以下代码来取消Url中的JSON数据。  但我的错误是:java.lang.String类型的值{“InvoiceNo”:18}无法转换为JSONObject.My Json喜欢:“{\”InvoiceNo \“:18}”请任何人帮助我。

    private class LongOperation extends AsyncTask{
    @Override
    protected Object doInBackground(Object[] params) {
        HttpResponse response = null;
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(
                    "http://192.168.1.2/Json/api/test"));
            response = client.execute(request);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }

        String responseText = null;
        try {
            responseText = EntityUtils.toString(response.getEntity());


        } catch (IOException e) {

            e.printStackTrace();


        }
        try {
            JSONObject json = new JSONObject(responseText); // **Error on this line**
            Iterator<String> keys = json.keys();

            while (keys.hasNext()) {
                String key = keys.next();
                String value = null;
                try {
                    value = json.getString(key);
                    Toast.makeText(Billing.this, value + "",
                            Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                 textInvoice.setText(value.toString());
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.i("responseText", responseText);

        return null;
    }
}

1 个答案:

答案 0 :(得分:1)

您的字符串不应包含字符"\"。如果是这样,这就是问题的原因。

相关问题