【问题标题】:Value is not coming while converting the String to JSON Object将字符串转换为 JSON 对象时没有出现值
【发布时间】:2016-01-05 17:00:51
【问题描述】:

我试图在 android 中解析来自 Wcf 服务的响应,但将我引导到空的 json 对象。所以在这里我附上我的代码,以便以字符串格式从 Wcf 服务获取响应,稍后我将其转换为 JSonObject。请看看这个并尝试告诉我为什么 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);
                                    }
                                }

                            }
                    }

【问题讨论】:

  • “缓冲区”里面有什么?你用调试器单步调试了吗?
  • buffer 包含字符串格式的 JSON ......哦,对不起,我忘记添加一行,即 jobject = jobject.getJSONObject("MyJsonGetMICData")。
  • 是的,它正在工作...感谢您的回复@Arsen
  • response.getStatusLine().getStatusCode() 返回什么?也许不是200?缓冲区中的 JSON 长什么样子,可能因为格式不正确而无法解析?
  • stackoverflow.com/questions/17260159/… 解释了类似的事情。

标签: android json wcf


【解决方案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;

【讨论】:

  • 感谢@NoChinDeluxe
  • 没问题。希望能帮助到你。如果您认为它解决了您的问题,请接受我的回答!
  • 什么是“jsonToSend”?
  • 您能否对此有所了解...。您提到的上述代码中的“jsonToSend”是什么...如果您有@NoChinDeluxe,请提供一些参考
  • @VikashKumar - 当然。所以在这种情况下,jsonToSend 是一个将 JSONObject POST 到 web 服务的示例,以获取 JSON 响应。在这个outputStreamWriter.write() 方法中,您只需发送Web 服务期望的任何请求。在我的示例中,我的 Web 服务期望 JSON 字符串作为请求,因此我只是将 Android JSONObject (jsonToSend) 转换为字符串。这有意义吗?
猜你喜欢
  • 2014-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 2019-08-27
  • 2020-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多