【Android】 在Andorid中解析Json数据示例

来源:互联网 发布:js给json对象添加属性 编辑:程序博客网 时间:2024/06/10 15:08


假设我们获取到的JSON数据如下图所示:



因为里面有需要显示的图片,直接在UI thread decode图片容易ANR,所以我们使用AsyncTask来处理:

【0】在OnResume里面去发出Http请求,获取到JSON数据

try    {DefaultHttpClient mDefaultHttpClient = new DefaultHttpClient();HttpGet mHttpGet = new HttpGet("http://music.weibo.com/yueku/xxxxxxx");HttpResponse mHttpResponse = mDefaultHttpClient.execute(mHttpGet);StringBuilder mStringBuilder = new StringBuilder();if(mHttpResponse.getStatusLine().getStatusCode() == 200){BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mHttpResponse.getEntity().getContent()));for(String str = mBufferedReader.readLine();str != null;str = mBufferedReader.readLine()){mStringBuilder.append(str);}}JSONObject mJSONObject = new JSONObject(mStringBuilder.toString());int resultCode = mJSONObject.getInt("retCode");if(resultCode==0){mbutton.setText("获取数据成功,解析如下:");cancelBackgroundAction();        asyncReqMusicInfo mAsyncReqMusicInfo = new asyncReqMusicInfo(mJSONObject.getJSONArray("Content"));        mAsyncReqMusicInfo.execute(0,0,0);}    }    catch (Exception localException)    {    logger.e("Error:"+localException);    }

【1】使用AsnycTask来进行解析数据,关键是里面需要decode bitmap,所以选择这个方式

class asyncReqMusicInfo extends AsyncTask<Integer, Integer, Integer>{JSONArrayJsonArray;ArrayList<MusicCategoryDetail>    MusicCategoryDetailList;asyncReqMusicInfo(JSONArray mJSONArray){this.MusicCategoryDetailList = new ArrayList<MusicCategoryDetail>();this.JsonArray = mJSONArray;}protected Integer doInBackground(Integer...params){logger.i("[asyncReqMusicInfo]");for(int i = 0;i < JsonArray.length();i++){JSONObject mJSONObject = (JSONObject) this.JsonArray.opt(i);MusicCategoryDetail mMusicCategoryDetail = new MusicCategoryDetail();try{mMusicCategoryDetail.setId(mJSONObject.getInt("id"));mMusicCategoryDetail.setName(mJSONObject.getString("name"));StringBuilder mStringBuilder = new StringBuilder("http://");mStringBuilder.append(mJSONObject.getString("image"));URL mURL = new URL(mStringBuilder.toString());logger.i("[mURL]"+mURL);Bitmap mBitmap = Activity02.this.getImageByURL(mURL);mMusicCategoryDetail.setImage(mBitmap);mMusicCategoryDetail.setUrl(mJSONObject.getString("url"));MusicCategoryDetailList.add(mMusicCategoryDetail);}catch(JSONException localJSONException){localJSONException.printStackTrace();}catch(MalformedURLException localMalformedURLException){localMalformedURLException.printStackTrace();}catch(IOException localIOException){localIOException.printStackTrace();}}return params[0];}protected void onPostExecute(Integer paramInteger){logger.d("onPostExecute");Activity2Adapter mActivity2Adapter = new Activity2Adapter(Activity02.this,MusicCategoryDetailList);Activity02.this.mListView.setAdapter(mActivity2Adapter);}}

【2】两个方法,一个使用得到的URL来获取bitmap,另外一个是处理AsyncTask的生命周期时会使用到

private Bitmap getImageByURL(URL paramURL) throws IOException{URLConnection mURLConnection = paramURL.openConnection();mURLConnection.connect();InputStream mInputStream = mURLConnection.getInputStream();BufferedInputStream mBufferedInputStream = new BufferedInputStream(mInputStream);Bitmap mBitmap = BitmapFactory.decodeStream(mBufferedInputStream);mBufferedInputStream.close();mInputStream.close();return mBitmap;}public void cancelBackgroundAction(){if(this.mAsyncReqMusicInfo != null){AsyncTask.Status localStatus1 = AsyncTask.Status.RUNNING;AsyncTask.Status localStatus2 = this.mAsyncReqMusicInfo.getStatus();if(localStatus1 == localStatus2)this.mAsyncReqMusicInfo.cancel(true);}this.mAsyncReqMusicInfo = null;}

【3】显示listView的adapter,这里使用自定义的Adapter,继承自baseAdapter

public class Activity2Adapter extends BaseAdapter{private MyLoggerlogger;private LayoutInflatermInflater;private ArrayList<MusicCategoryDetail>mMusicListItems;public Activity2Adapter(Activity paramActivity, ArrayList<MusicCategoryDetail> paramList){this.logger = MyLogger.kLog();this.mInflater = (LayoutInflater) paramActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);;this.mMusicListItems = paramList;logger.d("mMusicListItems.size:"+mMusicListItems.size());}public int getCount(){// TODO Auto-generated method stubreturn mMusicListItems.size();}public Object getItem(int position){// TODO Auto-generated method stubreturn mMusicListItems.get(position);}public long getItemId(int paramInt){return paramInt;}public View getView(int position, View convertView, ViewGroup parent){// TODO Auto-generated method stublogger.e("This is position:"+position);ImageView localImageView = null;TextView localTextView1 = null;TextView localTextView2 = null;TextView localTextView3 = null;MusicCategoryDetail localMusicCategoryDetail = (MusicCategoryDetail)getItem(position);if (localMusicCategoryDetail != null) {if (null == convertView) {logger.d("convertView == null,Then inflate and findViewById");convertView = mInflater.inflate(R.layout.listitem02, parent, false);localImageView = (ImageView) convertView.findViewById(R.id.listitem02ImageView);localTextView1 = (TextView) convertView.findViewById(R.id.listitem02TextView01);localTextView2 = (TextView) convertView.findViewById(R.id.listitem02TextView02);localTextView3 = (TextView) convertView.findViewById(R.id.listitem02TextView03);}else {logger.d("convertView != null,Then findViewById");localImageView = (ImageView) convertView.findViewById(R.id.listitem02ImageView);localTextView1 = (TextView) convertView.findViewById(R.id.listitem02TextView01);localTextView2 = (TextView) convertView.findViewById(R.id.listitem02TextView02);localTextView3 = (TextView) convertView.findViewById(R.id.listitem02TextView03);}if(null!=convertView){logger.d("convertView != null,Then SetValue");Util.setBitmap(localImageView, localMusicCategoryDetail.getImage());localTextView1.setText("[Id]:"+localMusicCategoryDetail.getId());localTextView2.setText("[Name]:"+localMusicCategoryDetail.getName());localTextView3.setText("[Url]:"+localMusicCategoryDetail.getUrl());}}return convertView;}}

【4】两个XML文件,一个是Activity的layout,另外一个是ListItem的layout

activity:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <Button android:id="@+id/activity02Button"android:layout_width="match_parent"android:layout_height=   "wrap_content" /><ListView    android:id                  =   "@+id/activity02ListView"    android:layout_width="fill_parent"android:layout_height=   "fill_parent"/></LinearLayout>
listItem:
<?xml version="1.0" encoding="utf-8"?><LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal">        <ImageView    android:id="@+id/listitem02ImageView"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:contentDescription="@string/desc"/>          <LinearLayout    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:orientation="vertical">    <TextView        android:id="@+id/listitem02TextView01"        android:layout_width="match_parent"    android:layout_height="wrap_content"/>    <TextView        android:id="@+id/listitem02TextView02"        android:layout_width="match_parent"    android:layout_height="wrap_content"/>    <TextView        android:id="@+id/listitem02TextView03"        android:layout_width="match_parent"    android:layout_height="wrap_content"/>"     </LinearLayout></LinearLayout>

最后解析结果如下图所示: