首页 > 技术文章 > 安卓开发之json解析

judes 2016-07-12 11:26 原文

1、从网页获取json返回字符串
 public class ReadNet extends AsyncTask<URL, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        protected String doInBackground(URL... params) {
            StringBuffer sb = new StringBuffer();
            try {
                HttpURLConnection connection = (HttpURLConnection) params[0].openConnection();
                InputStream is = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String readLine;
                while ((readLine = reader.readLine()) != null) {
                    sb.append(readLine);
                    sb.append("\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return sb.toString();//得到json
        }

        @Override
        protected void onPostExecute(String s) {

            Document doc = Jsoup.parse(s);
            showArticle.setText(doc.toString());
            super.onPostExecute(s);
        }
    }
2、用JSONObject类和JSONArray类解析json字符串
 JSONObject jsonObject = new JSONObject(jsonString);//{}
 JSONArray jsonArray = new JSONArray(jsonString);//[{1},{2}]
 JSONObject jsonObject = jsonArray.optJSONObject(1);

 Stirng str=jsonObject.optStirng("name"); 

 解析的可以放在list里面,建议都使用JsonObject来解析

 

彩蛋:

    optString和getString的区别:optStirng在得不到想要的结果时返回空,而getString抛出异常

推荐阅读