我正在开发PHP,Laravel和Android应用程序。
Laravel提供来自服务器的所有JSON数据(也需要一个网站),Android应用程序是消费者。
我正在尝试使用以下功能读取用户的所有组:
public function dataAllGroups($id)
{
if(isset($id)){
$user = User::find($id);
if(isset($user)){
$groups = UserGroup::where('status', '=', 'active')->where('user_id', $id)->get();
$queries = DB::getQueryLog();
$last_query = end($queries);
if(isset($groups) && count($groups)>0)
return array('message' => 'found', 'groups' => $groups, 'count' => count($groups), 'query' => $last_query);
else
return array('message' => 'empty', 'query' => $last_query);
}
else
return array('message' => 'invalid');
}
else
return array();
}
这将在logcat中返回以下内容
05-11 09:04:14.646 2531-2554/com.activetasks.activetasks D/group read result﹕ {"message":"found","groups":{},"count":2,"query":{"query":"select * from `user_groups` where `status` = ? and `user_id` = ?","bindings":["active","14"],"time":1}}
所以,查询是正确的,伯爵说我得到了2条记录,但是群组说{}
这对我来说有点奇怪。
这是我用于阅读JSON数组的Android逻辑:
protected String doInBackground(String... params) {
StringBuilder builder = new StringBuilder();
String result = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
try{
HttpResponse response = httpClient.execute(get);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = builder.toString();
}
catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
return result;
}
在这里,我阅读了返回的群组:
JSONArray jArray = json.getJSONArray("groups");
for(int i=0; i<jArray.length(); i++){
JSONObject json_data = jArray.getJSONObject(i);
Group group = new Group();
group.setId(json_data.getInt("id"));
group.setName(json_data.getString("name"));
groups.add(group);
}
groupAdapter.notifyDataSetChanged();
答案 0 :(得分:0)
groups
是您的JSONObject
而不是JSONArray
。
您需要从
更改 JSONArray jArray = json.getJSONArray("groups");
到
JSONObject Jb= json.getJSONObject("groups");
答案 1 :(得分:0)
我找到了解决方案。我将代码更改为:
&#39;组&#39; =&GT; $组 - &GT;指定者()
我正在获取群组数据。