我正在将PHP中的json_encoded数组返回给我的Android客户端。我首先从服务器收集数据,然后将其输入到名为“数据”的数组中:
$data[] = array('name'=>$name, 'distance'=>(int)$distance, 'city'=>$city, 'state'=>$state, 'interest'=>$interest, 'avatar'=>$avatar);
然后,我将该数组放入另一个数组中以获取一个count变量,这只是我的for循环中的增量。看起来像这样:
$response = array('data'=>$data, 'count'=>$count);
在Android方面,我使用以下方法检索此信息:
StringRequest searchPostRequest = new StringRequest(Request.Method.POST, searchURL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
mPlayerSuccess.start();
Log.d(TAG, "Complete Response: "+response);
JSONObject object = new JSONObject(response);
/*
*GET THE COMPLETE JSON ARRAY FROM SERVER
* ARRAY NAME IS "data"
* Strings are name, distance, city, state, interest, avatar
*/
JSONArray array = object.getJSONArray("data");
for(int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String name = jsonObject.getString("name");
int distance = jsonObject.getInt("distance");
String city = jsonObject.getString("city");
String state = jsonObject.getString("state");
String interest = jsonObject.getString("interest");
String avatar = jsonObject.getString("avatar");
String formatted_avatar = avatar.replace("\\", "");
int count = jsonObject.getInt("count");
Log.d(TAG, "Name Returned: "+name);
Log.d(TAG, "Distance Returned: "+distance);
Log.d(TAG, "City Returned: "+city);
Log.d(TAG, "State Returned: "+state);
Log.d(TAG, "Interest Returned: "+interest);
Log.d(TAG, "Avatar Returned: "+formatted_avatar);
Log.d(TAG, "Count: "+count);
这返回(在我的日志中):
D/MainActivity: Complete Response: {"data":[{"name":"lgill10","distance":296,"city":"Clinton","state":"IL","interest":"3D printing","avatar":"..\/users\/lgill10\/uploads\/dj-franklin.jpg"},{"name":"lgill9","distance":316,"city":"Bloomington","state":"IL","interest":"3D printing","avatar":"css\/images\/user_default\/default_avatar.png"},{"name":"testuser2","distance":14,"city":"Jonesboro","state":"AR","interest":"3D printing","avatar":"css\/images\/user_default\/default_avatar.png"}],"count":3}
但是,我得到的是“没有计数价值”,这导致所有“ Log.d”消息都无法显示。
我还尝试使用以下方法提取计数:
JSONArray count_array = object.getJSONArray("count");
JSONObject countObject = count_array.getJSONObject(0);
int count = countObject.getInt("count");
但是随后它捕获到异常并告诉我:
Value 3 at count of type java.lang.Integer cannot be converted to JSONArray
它返回正确的计数(3),但我不知道如何从多维数组中正确提取它。
如何获取计数值?我觉得这是一个小语法问题,我只是不知道如何纠正它。
答案 0 :(得分:0)
我希望我在问之前会想到这一点,但它只是突然出现在我身上。由于count变量实际上是数组长度,因此我使用以下命令进行访问:
...
Modelica.SIunits.Time t_star=-1;
equation
when p >= p_set then
t_star = time;
end when;
A = if t_star<0 then A_max else min(const*(t - t_star) + A_0, A_max);
返回:
int count = array.length();
Log.d(TAG, "Count: "+count);