[douban] 05_我读-每本书的详细介绍-json数据解析

Android 4.0

json数据解析

{} 每一个大括号里面的内容 就是一个json对象 ------- JSONObject
 
 
[] 代表一个json的数组,数组里面可以有多个{} ------- JSONArray
 
 
{}JSON对象里面的内容 必须是键值对的方式存放
如果 不是: JSONException
 
 
private void fillData(String isbn) {
        new AsyncTask<String, Void, Boolean>() {
            String title;
            String summary;
            String price;
            @Override
            protected Boolean doInBackground(String... params) {
                // http://api.douban.com/book/subject/isbn/7543632608?alt=json
                String path = "http://api.douban.com/book/subject/isbn/"
                        + params[0] + "?alt=json";
 
                try {
                    URL url = new URL(path);
 
                    Source source = new Source(url.openConnection());
                    String jsonstr = source.toString();
                    JSONObject jsonobj = new JSONObject(jsonstr);
                    String titlestr = jsonobj.get("title").toString();
                    JSONObject jsontitle = new JSONObject(titlestr);
                    title = jsontitle.get("$t").toString();
                    System.out.println(title);
 
                    String summarystr = jsonobj.get("summary").toString();
                    if (summarystr != null) {
                        JSONObject jsonsummary = new JSONObject(summarystr);
                        summary = jsonsummary.get("$t").toString();
                        System.out.println(summary);
                    }
                     
                    
                    String attributestr = jsonobj.get("db:attribute").toString();
                    JSONArray attributearray = new JSONArray(attributestr);
                    for(int i=0;i<attributearray.length();i++){
                        JSONObject jsonatt = new JSONObject( attributearray.get(i).toString());
                        if("price".equals( (jsonatt.get("@name").toString()))){
                            price = jsonatt.get("$t").toString();
                            System.out.println(price);
                        }
                    }
                    return true;
 
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
 
            }
 
            @Override
            protected void onPreExecute() {
                ll_loading.setVisibility(View.VISIBLE);
                super.onPreExecute();
            }
 
            @Override
            protected void onPostExecute(Boolean result) {
                ll_loading.setVisibility(View.INVISIBLE);
                if(result){
                    tv_title.setText(title+"/"+price);
                    tv_summary.setText(summary);
                }else{
                    Toast.makeText(getApplicationContext(), "查看详情失败", 1).show();
                }
                super.onPostExecute(result);
            }
 
        }.execute(isbn);
    }