Android 圖文資料JSON解析,金山詞霸每日一句API的調用

來源:互聯網
上載者:User

標籤:android開發   android   

金山詞霸開發的免費API http://open.iciba.com/dsapi/

資料格式為

{"sid":"737","tts":"http:\/\/news.iciba.com\/admin\/tts\/2013-12-11.mp3","content":"I don‘t want us to be together because we have to,I want us to be together because we want to.","note":"\u6211\u4e0d\u5e0c\u671b\u6211\u4eec\u56e0\u4e3a\u201c\u4e0d\u5f97\u4e0d\u201d\u800c\u5728\u4e00\u8d77\uff0c\u6211\u5e0c\u671b\u6211\u4eec\u662f\u56e0\u4e3a\u60f3\u5728\u4e00\u8d77\u800c\u5728\u4e00\u8d77\u3002","translation":"\u611f\[email protected]\u7a0b\u5f88\u591a\u8981\u79d2\u8650\u6570\u5b66 \u6295\u7a3f\u3002\u8bcd\u9738\u5c0f\u7f16\uff0c\u8fd9\u53e5\u8bdd\u6765\u81ea\u300a\u51b0\u6cb3\u4e16\u7eaa2\u300b\uff0c\u662f\u4e00\u4e2a\u7cfb\u5217\u7684\u52a8\u753b\u7535\u5f71\uff0c\u975e\u5e38\u641e\u7b11\uff0c\u4f60\u770b\u8fc7\u5417\uff1f","picture":"http:\/\/cdn.iciba.com\/news\/word\/2013-12-11.jpg","picture2":"http:\/\/cdn.iciba.com\/news\/word\/big_2013-12-11b.jpg","caption":"\u8bcd\u9738\u6bcf\u65e5\u4e00\u53e5","dateline":"2013-12-11","s_pv":"8693","sp_pv":"2090","tags":[{"id":"9","name":"\u7231\u60c5"},{"id":"14","name":"\u7535\u5f71\u7ecf\u5178"}],"fenxiang_img":"http:\/\/cdn.iciba.com\/web\/news\/longweibo\/imag\/2013-12-11.jpg"}

JSON欄位解釋

JSON 欄位解釋{‘sid‘:‘‘ #每日一句ID‘tts‘: ‘‘ #音頻地址‘content‘:‘‘ #英文內容‘note‘: ‘‘ #中文內容‘translation‘:‘‘ #詞霸小編‘picture‘: ‘‘ #圖片地址‘picture2‘: ‘‘ #大圖片地址‘caption‘:‘‘ #標題‘dateline‘:‘‘ #時間‘s_pv‘:‘‘ #瀏覽數‘sp_pv‘:‘‘ #語音評測瀏覽數‘tags‘:‘‘ #相關標籤‘fenxiang_img‘:‘‘ #合成圖片,建議分享微博用的}

最終實現的效果

具體實現,使用AsynTask非同步訪問網路:

class Load extends AsyncTask<String, String, String>    {        public String url = "http://open.iciba.com/dsapi/";        ProgressDialog pdlg;        String jsonstr = "";        JSONObject json = null;        @Override        protected String doInBackground(String... params) {            // TODO Auto-generated method stub            try{                DefaultHttpClient httpClient = new DefaultHttpClient();                HttpPost httppost = new HttpPost(url);                HttpResponse httpResponse = httpClient.execute(httppost);                HttpEntity httpEntity = httpResponse.getEntity();                InputStream is = httpEntity.getContent();                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));                StringBuilder sb = new StringBuilder();                String line = null;                while ((line = reader.readLine()) != null)                {                    sb.append(line + "\n");                }                is.close();                jsonstr = sb.toString();                json = new JSONObject(jsonstr.toString());                engstr = json.getString("content");                chistr = json.getString("note");                imagurl = json.getString("picture");                timestr =    json.getString("dateline");                fromstr   =  json.getString("translation");                JSONArray array = json.getJSONArray("tags");                for(int i=0;i<array.length();i++)                {                    JSONObject tag = (JSONObject)array.get(i);                    tagstr += tag.getString("name")+"," ;                 }            }catch(Exception e)            {                e.printStackTrace();            }                        return null;        }        @Override        protected void onPostExecute(String result) {            // TODO Auto-generated method stub            super.onPostExecute(result);            pdlg.dismiss();            imageLoader.DisplayImage(imagurl,imageview);            eng.setText("    "+engstr);            chi.setText("    "+chistr);            tag.setText(tagstr);            time.setText(timestr);            from.setText("    "+fromstr);        }        @Override        protected void onPreExecute() {            // TODO Auto-generated method stub            super.onPreExecute();            pdlg = new ProgressDialog(context);            pdlg.setCancelable(false);            pdlg.setMessage("正在載入");            pdlg.show();        }    }

使用了一個圖片處理的工具類,ImageLoader,主要用來通過url解析圖片,處理圖片的大小,以檔案的形式緩衝圖片。

public class ImageLoader {        MemoryCache memoryCache=new MemoryCache();    FileCache fileCache;    private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());    ExecutorService executorService;         public ImageLoader(Context context){        fileCache=new FileCache(context);        executorService=Executors.newFixedThreadPool(5);    }        final int stub_id = R.drawable.drug_trans;    public void DisplayImage(String url, ImageView imageView)    {        imageViews.put(imageView, url);        Bitmap bitmap=memoryCache.get(url);        if(bitmap!=null)            imageView.setImageBitmap(bitmap);        else        {            queuePhoto(url, imageView);            imageView.setImageResource(stub_id);        }    }            private void queuePhoto(String url, ImageView imageView)    {        PhotoToLoad p=new PhotoToLoad(url, imageView);        executorService.submit(new PhotosLoader(p));    }        private Bitmap getBitmap(String url)     {        File f=fileCache.getFile(url);                //from SD cache        Bitmap b = decodeFile(f);        if(b!=null)            return b;                //from web        try {            Bitmap bitmap=null;            URL imageUrl = new URL(url);            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();            conn.setConnectTimeout(30000);            conn.setReadTimeout(30000);            conn.setInstanceFollowRedirects(true);            InputStream is=conn.getInputStream();            OutputStream os = new FileOutputStream(f);            Utils.CopyStream(is, os);            os.close();            bitmap = decodeFile(f);            return bitmap;        } catch (Exception ex){           ex.printStackTrace();           return null;        }    }    //decodes image and scales it to reduce memory consumption    private Bitmap decodeFile(File f){        try {            //decode image size            BitmapFactory.Options o = new BitmapFactory.Options();            o.inJustDecodeBounds = true;            BitmapFactory.decodeStream(new FileInputStream(f),null,o);                        //Find the correct scale value. It should be the power of 2.            final int REQUIRED_SIZE=70;            int width_tmp=o.outWidth, height_tmp=o.outHeight;            int scale=1;            while(true){                if(width_tmp/1.5<REQUIRED_SIZE || height_tmp/1.5<REQUIRED_SIZE)                    break;                width_tmp/=1.5;                height_tmp/=1.5;                scale*=1.5;            }                        //decode with inSampleSize            BitmapFactory.Options o2 = new BitmapFactory.Options();            o2.inSampleSize=scale;            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);        } catch (FileNotFoundException e) {}        return null;    }        //Task for the queue    private class PhotoToLoad    {        public String url;        public ImageView imageView;        public PhotoToLoad(String u, ImageView i){            url=u;             imageView=i;        }    }        class PhotosLoader implements Runnable {        PhotoToLoad photoToLoad;        PhotosLoader(PhotoToLoad photoToLoad){            this.photoToLoad=photoToLoad;        }                @Override        public void run() {            if(imageViewReused(photoToLoad))                return;            Bitmap bmp=getBitmap(photoToLoad.url);            memoryCache.put(photoToLoad.url, bmp);            if(imageViewReused(photoToLoad))                return;            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);            Activity a=(Activity)photoToLoad.imageView.getContext();            a.runOnUiThread(bd);        }    }        boolean imageViewReused(PhotoToLoad photoToLoad){        String tag=imageViews.get(photoToLoad.imageView);        if(tag==null || !tag.equals(photoToLoad.url))            return true;        return false;    }        //Used to display bitmap in the UI thread    class BitmapDisplayer implements Runnable    {        Bitmap bitmap;        PhotoToLoad photoToLoad;        public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}        public void run()        {            if(imageViewReused(photoToLoad))                return;            if(bitmap!=null)                photoToLoad.imageView.setImageBitmap(bitmap);            else                photoToLoad.imageView.setImageResource(stub_id);        }    }    public void clearCache() {        memoryCache.clear();        fileCache.clear();    }}

其他精彩文章文章

jQuery教程(10)-DOM樹操作之內容setter和getter方法android學習筆記(37)使用 DatePickerDialog、TimePickerDialogandroid學習筆記(36)使用AlertDialog建立自訂對話方塊jQuery教程(1)-操作DOM之操作屬性Spring mvc新手入門(11)-返回json 字串的其他方式

更多關於android開發文章

Android 圖文資料JSON解析,金山詞霸每日一句API的調用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.