【发布时间】:2015-02-28 13:43:40
【问题描述】:
Android 中解析 JSON 时,只解析 10 项 JSON 数组。在调试时,我发现 connection.openConnection() ; 返回空查询字符串之后的查询字符串,例如http://www.example.com/recent_summary/?count=20 如果我将计数减少到 5,它仍然返回 10 个项目。但是,当我浏览棕色的 URL 时。它返回所有 20 项.. 我的代码有问题.. 服务器端工作正常,还有一件事,当我在 android Studio 中检查 openConnection() 声明(URL.java)时,我发现了很多红线..这里的菜鸟不知道它是否会有所帮助,但请帮帮我。
public class MainListActivity extends ActionBarActivity {
protected String TAG = MainListActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_list);
if(isNetworkAvailable()) {
GetPostsTask getPostsTask = new GetPostsTask();
getPostsTask.execute();
}else
{
Toast.makeText(this,"No Network", Toast.LENGTH_SHORT).show();
}
}
private boolean isNetworkAvailable(){
ConnectivityManager manager =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false ;
if (networkInfo != null && networkInfo.isConnected()){
isAvailable = true ;
}
return isAvailable;
}
private class GetPostsTask extends AsyncTask<Object, Void, String>{
protected String doInBackground(Object...arg){
JSONObject jsonResponse ;
try{
URL url = new URL(http://www.example.com/recent_summary/?count=20 );
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.connect();
int responseCode = connection.getResponseCode();
Log.i("Response Code", ""+responseCode);
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
BufferedReader r = new BufferedReader(reader);
StringBuffer buffer = new StringBuffer();
String line ;
while((line=r.readLine()) != null){
buffer.append(line + "\n");
}
Log.i("ResponseData" , ""+buffer);
jsonResponse = new JSONObject(buffer.toString());
JSONArray jsonPosts = jsonResponse.getJSONArray("posts") ;
for(int i =0 ; i<jsonPosts.length() ; i++){
JSONObject jsonPost = jsonPosts.getJSONObject(i);
String title = jsonPost.getString("title");
Log.i("Post"+i, title);
}
}catch (MalformedURLException ex){
Log.i(TAG , "Error Found ", ex);
}catch(IOException ex){
Log.i(TAG , "Error Found ", ex);
}catch (Exception ex){
Log.i(TAG , "Error Found ", ex);
}
return null ;
}
}
}
【问题讨论】:
-
分享 json 你得到什么回应?