Разбор json массива Java, Ошибка разбора данных org.json.JSONException

Это мой код, в моем журнале я получаю:

E / JSON Parser: Ошибка синтаксического анализа данных org.json.JSONException Значение xml типа java.lang.String не может быть преобразовано в 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);
}
?>

-1

Решение

Исходя из вашей ошибки, возвращаемый результат для makeHttpRequest представляет собой объект xml вместо форматированной строки json.

0

Другие решения

решаемая

ошибка произошла из-за неправильного URL, сервер Apache xampp возвращал объект не найден page..error 404, который представляет собой файл XML. Вот почему возвращаемый результат для makeHttpRequest — это объект xml вместо форматированной строки json.

0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector