我尝试构建一个Android应用程序,将参数发送到php代码作为where
在那个php代码中查询条件,我应该在log.i中查询查询结果但是
我收到以下错误
org.json.JSONException:java.lang.String类型的值john无法转换为JSONObject
MainActivity
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
JSONObject toSend = new JSONObject();
toSend.put("msg", "3");
JSONTransmitter transmitter = new JSONTransmitter();
transmitter.execute(new JSONObject[] {toSend});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
JSONTransmitter类。
public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {
String url = "http://192.168.1.10:89/b.php";
protected JSONObject doInBackground(JSONObject... data) {
JSONObject json = data[0];
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
JSONObject jsonResponse = null;
HttpPost post = new HttpPost(url);
try {
StringEntity se = new StringEntity("json="+json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);
HttpResponse response;
response = client.execute(post);
String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
jsonResponse=new JSONObject(resFromServer);
Log.i("Response from server", jsonResponse.getString("msg"));
Toast.makeText(null, resFromServer, Toast.LENGTH_LONG);
} catch (Exception e) { e.printStackTrace();}
return jsonResponse;
}
}
php code
<?php
mysql_connect("localhost", "root", "password")
or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$result = mysql_query(" select part_name from Services_parts where part_id= 1 ")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$j_out = new stdClass();
$j_out->part_name= $row['part_name'];
echo json_encode($j_out);
?>
答案 0 :(得分:0)
执行与此等效的代码:
JSONObject obj = new JSONObject("john");
显然会导致异常
这意味着来自服务器的json数据格式错误。问题可能在你的php代码里面,用于返回json中的项目数组,适应php + java代码:
$res_items = array();
for ( ... ) {
array_push($res_items, $some_item);
}
$js_result = get_json_encode(array(
"results" => $res_items
));
echo $js_result;
然后在java代码中:
JSONObject jsResp = new JSONObject(serverJsonResult);
JSONArray results = jsResp.getJSONArray("results");
for (int n = 0; n < results.length(); ++n) {
JSONObject js_row = results.getJSONObject(n);
// ...
}