将String转换为JSON对象时不会出现值

时间:2016-01-05 17:00:52

标签: android json wcf

我试图解析来自Android中Wcf服务的响应,但是引导我清空json对象。所以我在这里附上我的代码以便以字符串格式从Wcf服务获得响应我以后转换它到JSonObject.Please看看这个,并试着告诉我为什么Jsonobject是空的或没有值,

                    private JSONObject doWorkSheetResponse(String URL) {
                    // TODO Auto-generated method stub

                    String result = "";
                    JSONObject jobject = null;

                    DefaultHttpClient httpclient = new DefaultHttpClient();
                    HttpResponse response = null;

                    if (isConnected(getApplicationContext())) {
                        HttpGet httpget = new HttpGet(URL);
                        httpget.setHeader("Accept", "application/json");
                        httpget.setHeader("Content-type", "application/json");
                        try {
                            HttpParams httpParameters = httpget.getParams();
                            // Set the timeout in milliseconds until a
                            // connection is
                            // established.
                            int timeoutConnection = 120000;
                            HttpConnectionParams.setConnectionTimeout(
                                    httpParameters, timeoutConnection);
                            // Set the default socket timeout
                            // (SO_TIMEOUT)
                            // in milliseconds which is the timeout for
                            // waiting for data.
                            int timeoutSocket = 120000;
                            HttpConnectionParams.setSoTimeout(
                                    httpParameters, timeoutSocket);

                            response = httpclient.execute(httpget);

                            if (response != null) {

                                HttpEntity entity = response.getEntity();

                                if (entity != null) {
                                    /*

                                    // A Simple JSON Response Read

                                    InputStream instream = entity.getContent();
                                    result = convertStreamToString(instream);
                                    // now you have the string
                                    // representation of the HTML request
                                    System.out.println("RESPONSE: "
                                            + result);
                                    instream.close();
                                    if (response.getStatusLine()
                                            .getStatusCode() == 200) {
                                        jobject = new JSONObject(result);
                                    }

                                    */

//Currently using the below code
                                    String buffer = EntityUtils.toString(entity);   
                                    if (response.getStatusLine()
                                            .getStatusCode() == 200) {
                                        jobject = new JSONObject(buffer);
                                    }
                                }

                            }
                    }

1 个答案:

答案 0 :(得分:1)

Apache HTTP client is now deprecated您应该使用HttpURLConnection代替。尝试使用此代码从Web服务获取JSONObject:

//The JSON we will get back as a response from the server
JSONObject jsonResponse = null;

//Http connections and data streams
URL url;
HttpURLConnection httpURLConnection = null;
OutputStreamWriter outputStreamWriter = null;

try {

    //open connection to the server
    url = new URL("your_url_to_web_service");
    httpURLConnection = (HttpURLConnection) url.openConnection();

    //set request properties
    httpURLConnection.setDoOutput(true); //defaults request method to POST
    httpURLConnection.setDoInput(true);  //allow input to this HttpURLConnection
    httpURLConnection.setRequestProperty("Content-Type", "application/json"); //header params
    httpURLConnection.setRequestProperty("Accept", "application/json"); //header params
    httpURLConnection.setFixedLengthStreamingMode(jsonToSend.toString().getBytes().length); //header param "content-length"

    //open output stream and POST our JSON data to server
    outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
    outputStreamWriter.write(jsonToSend.toString());
    outputStreamWriter.flush(); //flush the stream when we're finished writing to make sure all bytes get to their destination

    //prepare input buffer and get the http response from server
    StringBuilder stringBuilder = new StringBuilder();
    int responseCode = httpURLConnection.getResponseCode();

    //Check to make sure we got a valid status response from the server,
    //then get the server JSON response if we did.
    if(responseCode == HttpURLConnection.HTTP_OK) {

        //read in each line of the response to the input buffer
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"utf-8"));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }

        bufferedReader.close(); //close out the input stream

        try {
            //Copy the JSON response to a local JSONObject
            jsonResponse = new JSONObject(stringBuilder.toString());
        } catch (JSONException je) {
            je.printStackTrace();
        }

} catch (IOException ioe) {
    ioe.printStackTrace();
} finally {
    if(httpURLConnection != null) {
        httpURLConnection.disconnect(); //close out our http connection
    }

    if(outputStreamWriter != null) {
        try {
            outputStreamWriter.close(); //close our output stream
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

//Return the JSON response from the server.
return jsonResponse;