如何像老师那样获取一个网页json数据?
如何像老师那样获取一个网页json数据?
如何像老师那样获取一个网页json数据?
2016-07-20
package com.example.myapplication; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.ListView; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.*; import java.io.InputStream; import java.io.InputStreamReader; import java.net.*; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private ListView listView; private String url = "http://www.imooc.com/api/teacher?type=4&num=30"; private List<NewsBean> newsBeenList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listView); MyAsyncTask myAsyncTask = new MyAsyncTask(); myAsyncTask.execute(url); } private List<NewsBean> getJsonData(String s){ List<NewsBean> listNews = new ArrayList<>(); NewsBean newsBean; try { String jsonString =readStream(new URL(s).openStream()); Log.i(TAG, "getJsonData: "+jsonString); JSONObject jsonObject = new JSONObject(jsonString); JSONArray jsonArray = jsonObject.getJSONArray("data"); for(int i=0;i<jsonArray.length();i++){ jsonObject = jsonArray.getJSONObject(i); newsBean = new NewsBean(); newsBean.newsIconUrl= jsonObject.getString("picSmall"); newsBean.title = jsonObject.getString("name"); newsBean.content = jsonObject.getString("description"); listNews.add(newsBean); } } catch (Exception e) { e.printStackTrace(); } return listNews; } public String readStream(InputStream is){ InputStreamReader isr; String result=""; try { String temp=""; isr = new InputStreamReader(is,"utf-8"); BufferedReader bufferedInputStream = new BufferedReader(isr); while((temp=bufferedInputStream.readLine())!=null){ result+=temp; } } catch (IOException e) { e.printStackTrace(); } return result; } class MyAsyncTask extends AsyncTask<String,Void,List<NewsBean>>{ @Override protected List<NewsBean> doInBackground(String... strings) { return getJsonData(strings[0]); } @Override protected void onPostExecute(List<NewsBean> newsBeen) { super.onPostExecute(newsBeen); newsBeenList = newsBeen; NewsAdapter newsAdapter = new NewsAdapter(newsBeenList,MainActivity.this); listView.setAdapter(newsAdapter); } } }
举报