0

My parser is this.jsonarraryParser.java

In this class, I want to convert the JSON response into a JSON array. Here my service returns more than on record. I want to convert it into a JSON array and then return the JSON array into my class.

Please tell me where I am doing wrong. Here is my code:

    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

My webservice

this is my web service, which is calling from the jsonarray parser class.

    <?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>

And Response:

When I am running the service in the browser it returns the JSON data in this format

 [{"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"}]
3

1 Answer 1

1

I think problem is in entity to string conversion. use EntityUtils to convert it.

E.g. code:

String response= EntityUtils.toString(entity); 

Complete javadoc is here http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/util/EntityUtils.html

Sign up to request clarification or add additional context in comments.

1 Comment

can any one tell me other technique

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.