当我将JSON数组转换为解析器时,它不会转换

问题描述 投票:0回答:1

我的解析器是this.jsonarraryParser.java

在该类中,我想将JSON响应转换为JSON数组。在这里,我的服务回报超过了记录。我想将其转换为JSON数组,然后将JSON数组返回到我的类中。

请告诉我我在哪里做错了。这是我的代码:

    package com.clockerp.connection;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.List;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.utils.URLEncodedUtils;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.util.Log;

    public class JSONArraryParser {

        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
        JSONArray jarray;

        // constructor
        public JSONArraryParser() {

        }

        // function get json from url
        // by making HTTP POST or GET mehtod
        @SuppressWarnings("unchecked")
        public JSONArray makeHttpRequest(String url, String method,
                @SuppressWarnings("rawtypes") List params) {

            // Making HTTP request
            try {

                // check for request method
                if(method == "POST"){
                    // request method is POST
                    // defaultHttpClient
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(url);
                    httpPost.setEntity(new UrlEncodedFormEntity(params));

                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
                    Log.e("Json ArrRY ", " httpEntity -------------"+is.toString()); 

                    String str = is.toString() ;

                    Log.e("Json ArrRY ", str);



                    try{
                         if (httpEntity != null) {
                         jarray = new JSONArray(str);
                         Log.e("Json ArrRY ", jarray.toString());
                          }


                    }catch(Exception n)
                    {
                         Log.e("Json ArrRY ", " Error In parsing "+n.getMessage()); 

                        n.printStackTrace();
                    }

                    Log.e("Json ArrRY ", " result " + jarray .toString()); 


                  Log.e("HTTP RESPONSE 1is", " result " + is.toString());

                }else if(method == "GET"){
                    // request method is GET
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;
                    HttpGet httpGet = new HttpGet(url);

                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
    //              



                }           

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

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"),10);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + " ");
                }

                is.close();

                json = sb.toString();


            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }

            // try parse the string to a JSON object
    //        try {
    //         //   jObj = new JSONObject(json);
    //            
    //        } catch (JSONException e) {
    //            Log.e("JSON Parser", "Error parsing data " + e.toString());
    //        }


            // return JSON String
            return jarray;

        }
    }

Logcat:

    04-08 11:03:12.425: E/himanshu(1263): http://192.168.1.148/clock/webservice/student_libraray_info1.php
    04-08 11:03:12.425: E/request!(1263): starting
    04-08 11:03:14.791: E/Json ArrRY(1263):  httpEntity -------------org.apache.http.conn.EofSensorInputStream@3fced0cb
    04-08 11:03:14.792: E/Json ArrRY(1263): org.apache.http.conn.EofSensorInputStream@3fced0cb
    04-08 11:03:14.821: E/Json ArrRY(1263):  Error In parsing Value org.apache.http.conn.EofSensorInputStream@3fced0cb of type java.lang.String cannot be converted to JSONArray

我的网络服务

这是我的Web服务,它是从jsonarray解析器类中调用的。

    <?php
    //load and connect to MySQL database stuff
    include('../includes/config.php');

    ?>



    <? ############################################################################################# ?>
    <? 
    if (!empty($_POST)) {

     $query = "SELECT book_log.`issue_date`,book_log.`due_date`,book_log.`status`,employees.`first_name`,employees.`middle_name`,employees.`last_name`,books.`title` from book_log inner join employees on book_log.`librarian_id`=employees.`id` inner join books on book_log.`book_id`=books.`id` where book_log.`user_id`=(select id from users where username='".$_POST['username']."')";
    $info=mysql_query($query) or die (mysql_error());
       $data=array();
        if(mysql_num_rows($info)>0)
              {
                 while($row=mysql_fetch_array($info))
                 {


                $response["issue_date"]=$row['issue_date'];
                    $response["due_date"]=$row['due_date'];
                $response["status"]=$row['status'];

                $response["first_name"]=$row['first_name'];
                $response["middle_name"]=$row['middle_name'];
                $response["last_name"]=$row['last_name'];

                $response["title"]=$row['title'];
               $data[]=$response;
               }
            $json=array('data'=>$data);
            echo json_encode($data);

              }
      else
       {
             $response["success"] = 0;
            $response["message"] = "Invalid Student_Id!";
            die(json_encode($response));

        }    

    }

    ?>

    <form action="#" method="post">
      Username:<br />
      <input type="text" name="username" placeholder="username" />
      <br />
      <br />
      Password:<br />
      <input type="password" name="password" placeholder="password" value="" />
      <br />
      <br />
      <input type="submit" value="Login" />
    </form>

和回应:

当我在浏览器中运行服务时,它将以这种格式返回JSON数据

 [{"issue_date":"2015-03-19","due_date":"2015-04 03","status":"Issued","first_name":"Admin","middle_name":"","last_name":"User","   title":"Business Statistics"},{"issue_date":"2015-03-19","due_date":"2015-04-03","status":"Issued","first_name":"Admin","middle_name":"","last_name":"User","title":"Marketing Research"}]
android json
1个回答
0
投票

我认为问题在于实体到字符串的转换。使用EntityUtils进行转换。

例如代码:

String response= EntityUtils.toString(entity); 

完整的javadoc在这里http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/util/EntityUtils.html

© www.soinside.com 2019 - 2024. All rights reserved.