android 之json对象解析并展示(含json解析源码)

具体处理思路以及使用到的知识点:

1.使用android的异步处理

2.将要使用的功能(方法)进行封装,以便主类进行调用

3.前台展示要使用适配器模型(这里使用简单适配器(SimpleAdapter))

主类的代码:

package com.example.lenovo.asynctask_json;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.example.lenovo.asynctask_json.domin.NetUtils;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
/**
 * {}代表 json对象
 * []:代表时json 数组
 *
 * {key:value,key:value,key:value.....}
 *
 * {
 *  name:"张三",
 *
 *  age:20,
 *
 *  tel:[111,222,333,444],
 *
 *  loves:[
 *      {ball:"球"},
 *      {game:"游戏"}
 *
 *  ]
 *
 *  }
 */
public class MainActivity extends AppCompatActivity {
    private ListView listView_movie;
    private SimpleAdapter adapter;
    private List> list;
    //private String  path="http://lib.wap.zol.com.cn/ipj/docList.php?class_id=0&page=1&vs=and380&retina=1
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.listView_movie= (ListView) this.findViewById(R.id.listView_movie);
        String  path= null;
        try {
            //URLEncoder.encode("热门","utf-8"):将汉字进行Unicode编码
            path = "https://movie.douban.com/j/search_subjects?type=movie&tag="+ URLEncoder.encode("热门","utf-8")+"&sort=recommend&page_limit=20&page_start=21";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        new NetDownLoadAsyncTask().execute(path);
    }
    private final class NetDownLoadAsyncTask extends AsyncTask>>{
        @Override
        protected List> doInBackground(String... params) {

            //调用NetUtils类的方法,将网址对应的数据以InputStream的形式返回.
            InputStream inputStream=NetUtils.getInputStreamByPath(params[0]);

            if(inputStream!=null){
                //调用NetUtils类的方法,将输入流转换成字符串.
                String json=NetUtils.getStringByInputStream(inputStream);
                System.out.println("json="+json);

                if(json!=null){
                    //调用NetUtils类的方法,对json对象进行处理
                    list= NetUtils.getListMapByJsonString(json);
                    return list;
                }
            }
            return null;
        }
        @Override
        protected void onPostExecute(List> maps) {
            if(maps!=null){
                System.out.println("maps="+maps);
                adapter=new SimpleAdapter(
                        MainActivity.this,//上下文对象
                        maps,//数据源
                        R.layout.movie_item,//前台要展示的,这里是(自己定义到格式)对应点击条目的样式
                        new String[]{"title","cover"},//键值"title"与"cover"
             
                        new int[]{R.id.textView_title,R.id.imageView_cover}//控件对应id的int型数组
                ){
                    /**
                     * 当每绘制一条条目对象时自动调用的方法
                     * @param position
                     * @param convertView
                     * @param parent
                     * @return
                     */
                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {
                        //System.out.println("===getView(int position="+position+", View convertView="+convertView+", ViewGroup parent="+parent+")===");
                        //得到当前绘制的条目对象
                        View view=super.getView(position, convertView, parent);
                        //System.out.println("view="+view);
                        ImageView imageView_cover= (ImageView) view.findViewById(R.id.imageView_cover);
                        Map map=list.get(position);
                        Bitmap bitmap= (Bitmap) map.get("cover");
                        //手工设置imageView对应的bitmap对象
                        imageView_cover.setImageBitmap(bitmap);
                        return view;
                    }
                };
                listView_movie.setAdapter(adapter);
                System.out.println("=======");
            }else {
                System.out.println("从网络上获取数据失败!");
            }
        }
    }
}

封装好的代码:

package com.example.lenovo.asynctask_json.domin;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hsjwcf on 2018/5/29.
 */
public class NetUtils {

    /**
     * 将给你的网址对应的数据以InputStream的形式返回
     * @param path
     * @return
     */
    public static InputStream getInputStreamByPath(String path){
        try {
            URL url=new URL(path);
            HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(3000);

            /*
            httpURLConnection.getResponseCode()干了两件事:
            A:根据指定的网址向服务器发送请求并得到服务器的回应
            B:在回应中包含状态码:200表示访问成功

             */
            int responseCode=httpURLConnection.getResponseCode();
            if(responseCode==200){//说明本次访问成功
                //以输入流的形式得到服务器返回的数据
                InputStream inputStream=httpURLConnection.getInputStream();
                return inputStream;

            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 根据输入流得到字节数组
     * @param inputStream
     * @return
     */
    public static byte[]  getBytesByInputStream(InputStream inputStream){
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        byte[] buffer=new byte[1024];
        int len=0;

        try {
            while ((len=inputStream.read(buffer))!=-1){
                byteArrayOutputStream.write(buffer,0,len);
            }

            return  byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 根据输入流得到字符串
     * @param inputStream
     * @return
     */
    public static String getStringByInputStream(InputStream inputStream){
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        byte[] buffer=new byte[1024];
        int len=0;

        try {
            while ((len=inputStream.read(buffer))!=-1){
                byteArrayOutputStream.write(buffer,0,len);
            }

            return  byteArrayOutputStream.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 通过解析json 字符串得到List>类型的对象
     *
     *
     * {
     "subjects": [
     {
     "rate": "8.3",
     "cover_x": 3578,
     "title": "暴裂无声",
     "url": "https://movie.douban.com/subject/26647117/",
     "playable": true,
     "cover": "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2517333671.jpg",
     "id": "26647117",
     "cover_y": 5078,
     "is_new": false
     },

     {
     "rate": "7.0",
     "cover_x": 1500,
     "title": "负重前行",
     "url": "https://movie.douban.com/subject/26793157/",
     "playable": false,
     "cover": "https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2518648419.jpg",
     "id": "26793157",
     "cover_y": 2222,
     "is_new": false
     }
     ]
     }

     * @param json
     * @return
     */
    public static List> getListMapByJsonString(String json){

        List> list=new ArrayList<>();

        try {
            //1.将json 字符串转换成Json对象
            JSONObject jsonObject=new JSONObject(json);

            //2.根据键得到json 数组
            JSONArray jsonArray=jsonObject.getJSONArray("subjects");
            //得到数组中元素的个数
            int len=jsonArray.length();
            for(int i=0;i map=new HashMap<>();
                jsonObject= jsonArray.getJSONObject(i);
                String title=jsonObject.getString("title");
                String cover=jsonObject.getString("cover");

                System.out.println("cover="+cover);
                //String cover=jsonArray.getString(0);



                map.put("title",title);
                //将数据源中cover 对应的网址转换成Bitmap 对象
                InputStream inputStream=getInputStreamByPath(cover);
                byte[] data=getBytesByInputStream(inputStream);
                Bitmap bitmap=BitmapFactory.decodeByteArray(data,0,data.length);

                map.put("cover",bitmap);

                list.add(map);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }
}

前台展示:

<1>




    
    

<2>



    



你可能感兴趣的:(android)