Java解析json数组,解析数据时出错org.json.JSONException

时间:2017-03-29 19:37:02

标签: java php json arraylist

这是我的代码,在我的日志中,我得到了:

  

E / JSON Parser:解析数据时出错org.json.JSONException java.lang.String类型的值xml无法转换为JSONObject

我真的需要一个我已经搜索了几周的解决方案。

    @Override
    protected String doInBackground(String... para) {

        List<NameValuePair> params=new ArrayList<NameValuePair>();
        JSONObject json=jparser.makeHttpRequest(getDataUrl, "POST", params);

        try {
            success=json.getInt("success");
            if(success==1){

                drivers=new ArrayList<Driver>();

                JSONArray sounds=json.getJSONArray("location");
                for (int i = 0; i < sounds.length(); i++) {
                    JSONObject jobj=sounds.getJSONObject(i);
                    Driver d=new Driver();
                    d.setId(jobj.getString("id"));
                    d.setName(jobj.getString("name"));
                    d.setEmail(jobj.getString("email"));
                    d.setNumber(jobj.getString("number"));
                    d.setLatitude(jobj.getString("latitude"));
                    d.setLongitude(jobj.getString("longitude"));
                    d.setInfo(jobj.getString("info"));
                    d.setCost(jobj.getString("cost"));
                    drivers.add(d);

                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
            error=1;
        }catch (Exception e) {
            error=1;
        }
        return null;
    }

这是JSONParser类

JSONParser.java

public class JSONParser {

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

    // constructor
    public JSONParser() {
    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {
            // check for request method
            if(method.equals("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();

            } else if(method.equals("GET")) {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();

                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"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            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 jObj;
    }
}

PHP文件

<?php
header('Content-Type: application/json');

$response = array();

// include db connect class
require_once 'core/db_connect.php';
$db = new DB_CONNECT();

$sql="SELECT * FROM locations WHERE online=1";
$result = mysqli_query($db->connect(), $sql) or die(mysqli_error($db->connect()));

if (mysqli_num_rows($result)>0) {
    $response["location"] = array();
        while ($row=mysqli_fetch_array($result)) {
            $files=array();
            $files["id"]=$row["id"];
            $files["name"]=$row["name"];
            $files["email"]=$row["email"];
            $files["number"]=$row["number"];
            $files["latitude"]=$row["latitude"];
            $files["longitude"]=$row["longitude"];
            $files["info"]=$row["vehicleinfo"];
            $files["cost"]=$row["costpkm"];

            array_push($response["location"], $files);

    }

    $response["success"]=1;
    echo json_encode($response);
} else {
    $response["success"]=0;
    $response["message"]="No Taxi found";

    echo json_encode($response);
}
?>

2 个答案:

答案 0 :(得分:0)

根据您的错误,makeHttpRequest的返回结果是xml对象而不是json格式化字符串。

答案 1 :(得分:0)

<强>解决

  

错误是由于url不正确,xampp apache服务器返回了一个找不到的对象page..error 404,这是一个xml文件。这就是makeHttpRequest的返回结果是xml对象而不是json格式化字符串的原因。