我收到了这个错误:
org.json.JSONException:org.json.JSONArray类型的值[]无法转换为JSONObject
我试图根据过滤器显示android app中的数据库中的一些记录。邮差告诉我正确的结果显示错误。我在第二个应用程序中使用基本相同的方法,它可以工作。
PHP脚本:
function findUsers($odkial, $co){
$stmt = $this->con->prepare("SELECT Meno, RodneCislo, PIK FROM zamestnanci WHERE $odkial LIKE ?");
$stmt->bind_param("s", $co);
$stmt->execute();
$stmt->bind_result($Meno, $RC, $PIK);
$foundUsers = array();
while($stmt->fetch()){
$user = array();
$user['meno'] = $Meno;
$user['rodnecislo'] = $RC;
$user['pik'] = $PIK;
array_push($foundUsers, $user);
}
return $foundUsers;
}
从编辑文本和微调器中获取一些参数的Android代码方法:
public void hladajZaznamy(){
HashMap<String, String> params = new HashMap<>();
String pod = podla.getSelectedItem().toString();
String co = "%"+podlac.getText().toString()+"%";
params.put("PodlaCoho", pod);
params.put("Co", co);
PerformNetworkRequest request = new PerformNetworkRequest(Api.HLADAJ_ZAMESTNANCA, params, CODE_POST_REQUEST);
request.execute();
}
Android code networkrequest:
private class PerformNetworkRequest extends AsyncTask<Void, Void, String> {
String url;
HashMap<String, String> params;
int requestCode;
PerformNetworkRequest(String url, HashMap<String, String> params, int requestCode) {
this.url = url;
this.params = params;
this.requestCode = requestCode;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject object = new JSONObject(s); // HERE IS THE ERROR
if (!object.getBoolean("error")) {
Toast.makeText(getApplicationContext(), object.getString("message"), Toast.LENGTH_SHORT).show();
saveRecords(object.getJSONArray("foundUsers"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//the network operation will be performed in background
@Override
protected String doInBackground(Void... voids) {
RequestHandler requestHandler = new RequestHandler();
if (requestCode == CODE_POST_REQUEST)
return requestHandler.sendPostRequest(url, params);
if (requestCode == CODE_GET_REQUEST)
return requestHandler.sendGetRequest(url);
return null;
}
}
例如,当PodlaCoho = Meno
和Co = %TESTTEST%
:
{"error":false,"message":"Zamestnanci uspesne vyhladani","foundUsers":[{"meno":"TESTTEST","rodnecislo":"1111225555","pik":"111111"}]}
感谢您的任何建议:)
答案 0 :(得分:0)
这是因为您要转换为JSONObject
的响应字符串应采用JSONArray
的形式,因此请将错误行更改为此。
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
JSONArray objectArray = new JSONArray();
for (int i = 0; i < objectArray.length(); i++) {
//here you can iterate through the array elements and find respective JSONObject and/or other values.
}
}
希望这会有所帮助..