无法在Response.Listener上将java.lang.String类型的值转换为JSONObject

时间:2016-07-04 09:47:31

标签: java android json android-volley

您好我在检索数据时遇到此问题,我使用android volley和json从Web服务器获取数据。

继承我的php文件:

<?php
    $con = mysqli_connect("***", "***", "***", "***");

    // listing input entries for query
    $city = $_POST["city"];
    $term = $_POST["term"];
    $p_type = $_POST["property_type"];
    $min = $_POST["price_min"];
    $max = $_POST["price_max"];
    $bedrooms = $_POST["bedrooms"];
    $bathrooms = $_POST["bathrooms"];

    $query = "SELECT * FROM listing WHERE city = ? AND term = ? AND property_type = ? AND bedrooms = ? AND bathrooms = ?
    AND price BETWEEN ? AND ?";

    $statement = mysqli_prepare($con, $query);
    mysqli_bind_param($statement, "sssiiii", $city, $term, $p_type, $bedrooms, $bathrooms, $min, $max);
    mysqli_stmt_execute($statement);

    mysqli_stmt_store_result($statement);
    mysqli_stmt_bind_result($statement, $p_id, $p_name, $p_type, $term, $city, $address, $lot_area, $floor_area, $price, 
        $bedrooms, $bathrooms, $host_name, $host_contact_no, $host_details, $date_listed, $user_id);

    $count = mysqli_stmt_num_rows($statement);
    mysqli_stmt_close($statement); 

    $response = array();
    $response["hasData"] = false;

    if($count > 0){
        $response["hasData"] = true;
        while(mysqli_stmt_fetch($statement)){
            $response["property_name"]= $p_id;
            $response["property_type"] = $p_type;
            $response["term"] = $term;
            $response["city"] = $city;
            $response["address"] = $address;
            $response["lot_area"] = $lot_area;
            $response["floor_area"] = $floor_area;
            $response["price"] = $price;
            $response["bedroom"] = $bedroom;
            $response["bathroom"] = $bathroom;
            $response["host_name"] = $host_name;
            $response["host_contact_no"] = $host_contact_no;
            $response["host_details"] = $host_details;
            $response["date_listed"] = $date_listed;
        }

    }else{
        $response["hasData"] = false;
    }

    echo json_encode($response);
?>

我有一个java类名searchListingRequest.java

public class SearchListingRequest extends StringRequest {

    private static final String SEARCH_REQUEST_URL = "http://homeseek.netau.net/searchLising.php";
    private Map<String, String> params;

    public SearchListingRequest(String city, String term, String p_type,
                                int price_min, int price_max, int bedrooms, int bathrooms, Response.Listener<String> listener){
        super(Method.POST, SEARCH_REQUEST_URL, listener, null);
        params = new HashMap<>();
        params.put("city", city);
        params.put("term", term);
        params.put("property_type", p_type);
        params.put("price_min", price_min + "");
        params.put("price_max", price_max + "");
        params.put("bedrooms", bedrooms + "");
        params.put("bathrooms", bathrooms + "");
    }

    @Override
    public Map<String, String> getParams() {
        return params;
    }

}

在我的另一个类ShowResults.java中,我调用上面的类来创建实例并发出一个http请求:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_results);
        //unfocus on edittexts when starting
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        //gets data from home fragment
        Intent intent = getIntent();

        //initialize listview
        data_listing = (ListView) findViewById(R.id.lv_data_listing);

        retrieveData(showResults, intent, data_listing);

    }

    public void retrieveData(Activity activity,Intent intent, final ListView lv){
        final String inputCity = intent.getStringExtra("city");
        final String inputTerm = intent.getStringExtra("term");
        final String inputType = intent.getStringExtra("type");
        final int inputPMin = Integer.parseInt(intent.getStringExtra("price_min"));
        final int inputPMax = Integer.parseInt(intent.getStringExtra("price_max"));
        final int inputBedrooms = Integer.parseInt(intent.getStringExtra("bedrooms"));
        final int inputBathrooms = Integer.parseInt(intent.getStringExtra("bathrooms"));

        test = (TextView) findViewById(R.id.tv_test);

        Response.Listener<String> responseListener = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {

                    JSONObject jsonResponse = new JSONObject(response);
                    JSONArray responseArray = new JSONArray(response);
                    boolean hasData = jsonResponse.getBoolean("hasData");

//                    check if has data
                        if(hasData){
                            test.setText("have data");
                    }
                    else{// no data retrieved
                        showAlertDialog();
                            test.setText("no data");
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Can't connect to server.", Toast.LENGTH_SHORT).show();
                    test.setText("error");
                }
            }
        };

        SearchListingRequest searchListingRequest =
                new SearchListingRequest(inputCity,inputTerm,inputType,inputPMin,inputPMax,inputBedrooms,inputBathrooms,responseListener);
        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        queue.add(searchListingRequest);
    }

当我运行应用程序时,文本显示“错误”,这意味着它有一个jsonexception。

这是logcat:

Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

我真的不知道这意味着什么。谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

这是因为默认情况下,volley不会以JSON格式发送POST主体,我认为服务器期望JSON中的POST主体。因此,您需要覆盖getBody()方法并将格式从application / x-www-form-urlencoded更改为json。

请参阅以下代码:

 @Override
    public bytes[] getBody() {
        new JSONObject(params).toString().getBytes();
    }
  

还要考虑重写getBodyContentType并将其设置为JSON。