http通信之Json数据解析

如何制作Json格式的数据

  利用Google 提供的gson-2.2.4.jar,

    

public class TestJson {

	public static void main(String[] args) {

		Result result = new Result();
		result.setResult(1);
		List<People> peoples = new ArrayList<>();
		People people1 = new People();
		people1.setName("jack");
		people1.setAge(13);
		people1.setUrl("http://hiphotos.baidu.com/9_6kis/pic/item/3b8fe9df2b11c37695ee37c4.jpg");
		List<SchoolInfo> schoolInfo1 = new ArrayList<>();
		SchoolInfo school1 = new SchoolInfo();
		school1.setSchool_name("清华");
		schoolInfo1.add(school1 );
		SchoolInfo school2 = new SchoolInfo();
		school2.setSchool_name("北大");
		schoolInfo1.add(school2 );
		people1.setSchoolInfo(schoolInfo1 );
		peoples.add(people1);
		
		People people2 = new People();
		people2.setName("rose");
		people2.setAge(13);
		people2.setUrl("http://hiphotos.baidu.com/a03713106460/pic/item/772181666066aa0faa184c1d.jpg");
		List<SchoolInfo> schoolInfo2 = new ArrayList<>();
		SchoolInfo school3 = new SchoolInfo();
		school3.setSchool_name("人大");
		schoolInfo2.add(school3 );
		SchoolInfo school4 = new SchoolInfo();
		school4.setSchool_name("交大");
		schoolInfo2.add(school4 );
		people2.setSchoolInfo(schoolInfo2 );
		peoples.add(people2);
		
		result.setPersonData(peoples);
		
		Gson gson = new Gson();
		System.out.println(gson.toJson(result));
	}

}

    制作完成的Json数据放入http://www.bejson.com网站中格式化验证

   结果:

{
    "result": 1,
    "personData": [
        {
            "name": "jack",
            "age": 13,
            "url": "http://hiphotos.baidu.com/9_6kis/pic/item/3b8fe9df2b11c37695ee37c4.jpg",
            "schoolInfo": [
                {
                    "school_name": "清华"
                },
                {
                    "school_name": "北大"
                }
            ]
        },
        {
            "name": "rose",
            "age": 13,
            "url": "http://hiphotos.baidu.com/a03713106460/pic/item/772181666066aa0faa184c1d.jpg",
            "schoolInfo": [
                {
                    "school_name": "人大"
                },
                {
                    "school_name": "交大"
                }
            ]
        }
    ]
}

 

1.开启线程访问网络

       访问网络并且将Json格式的数据读取出来,进行Json解析

     

public class HttpJson extends Thread {

    private String url;
    private ListView listView;
    private JsonAdapter adapter ;
    private Handler handler;
    private Context context;
    private static final String TAG = "HttpJson";

    public HttpJson(String url, Context context, ListView listView, JsonAdapter adapter, Handler handler){
        this.url = url;
        this.listView = listView;
        this.adapter = adapter;
        this.handler = handler;
        this.context = context;
    }

    @Override
    public void run() {
        try {
            URL httpurl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpurl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            //从输入流中取得Josn数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String str ;
            while((str = reader.readLine()) != null){
                sb.append(str);
            }
            Log.i(TAG, "run: " + sb.toString());
            final List<People> peoples = parserJson(sb.toString());
            for ( People people : peoples){
                Log.i(TAG, "run: " + people.toString());
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    adapter.setPeoples(peoples);
                    listView.setAdapter(adapter);
                }
            });
            reader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析Json数据
     * @param json
     */
    private List<People> parserJson(String json) {
        /*
         *{"result":1,"personData":[{"name":"jack","age":13,"url":"http://hiphotos.baidu.com/9_6kis/pic/item/3b8fe9df2b11c37695ee37c4.jpg","schoolInfo":[{"school_name":"清华"},{"school_name":"北大"}]},{"name":"rose","age":13,"url":"http://hiphotos.baidu.com/a03713106460/pic/item/772181666066aa0faa184c1d.jpg","schoolInfo":[{"school_name":"人大"},{"school_name":"交大"}]}]}
         * 可放入www.bejson.com 网站Josn解析器中解析
         */
        try {
            JSONObject jsonObject = new JSONObject(json);
            List<People> peoples=  new ArrayList<>();
            int result = jsonObject.getInt("result");
            if(result == 1) {
                JSONArray personData = jsonObject.getJSONArray("personData");
                for(int i = 0 ;i < personData.length();i++){
                    People peopleObject = new People();
                    peoples.add(peopleObject);
                    JSONObject object = personData.getJSONObject(i);
                    String name = object.getString("name");
                    int age = object.getInt("age");
                    String imageUrl = object.getString("url");
                    peopleObject.setName(name);
                    peopleObject.setAge(age);
                    peopleObject.setUrl(imageUrl);
                    JSONArray schoolInfos = object.getJSONArray("schoolInfo");
                    List<SchoolInfo> schInfos = new ArrayList<>();
                    for(int j = 0;j < schoolInfos.length();j++){
                        JSONObject schoolObject = schoolInfos.getJSONObject(j);
                        SchoolInfo school = new SchoolInfo();
                        String school_name = schoolObject.getString("school_name");
                        Log.i(TAG, "parserJson: " + school_name);
                        school.setSchool_name(school_name);
                        schInfos.add(school);
                    }
                    peopleObject.setSchoolInfo(schInfos);
                }
                return  peoples;
            }else{
                Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}

2.接着就是JsonAdapter的实现

   其中就是ListView 的用了,在getView里面,开启线程HttpImage去访问网络加载图片,

     

public class JsonAdapter extends BaseAdapter{

    private static final String TAG = "JsonAdapter";
    private Context context;
    private List<People> peoples;
    private LayoutInflater inflater;
    private Handler handler;

    public JsonAdapter(Context context,Handler handler){
        this.context = context;
        this.handler = handler;
        inflater = LayoutInflater.from(context);
    }

    public List<People> getPeoples() {
        return peoples;
    }

    public void setPeoples(List<People> peoples) {
        this.peoples = peoples;
    }

    @Override
    public int getCount() {
        return peoples.size();
    }

    @Override
    public Object getItem(int position) {
        return peoples.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(convertView == null){
            convertView = inflater.inflate(R.layout.item_listview,null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }
        People people = peoples.get(position);
        if(people != null)
            Log.i(TAG, "getView: " + people.toString());
        holder.name.setText(people.getName());
        holder.age.setText("" + people.getAge());
        holder.school1.setText(people.getSchoolInfo().get(0).getSchool_name());
        holder.school2.setText(people.getSchoolInfo().get(1).getSchool_name());
        new HttpImage(people.getUrl(),handler,holder.imageView).start();
        return convertView;
    }

}
class  ViewHolder {
    ImageView imageView;
    TextView name;
    TextView age;
    TextView school1;
    TextView school2;
    public ViewHolder(View view){
        imageView = (ImageView) view.findViewById(R.id.imageView);
        name = (TextView) view.findViewById(R.id.tv_name);
        age = (TextView) view.findViewById(R.id.tv_age);
        school1 = (TextView) view.findViewById(R.id.school1);
        school2 = (TextView) view.findViewById(R.id.school2);
    }
}

 3.加载图片线程httpImage

public class HttpImage extends Thread{

    private String url;
    private Handler handler;
    private ImageView imageView;
    public HttpImage(String url, Handler handler, ImageView imageView) {
        this.url = url;
        this.handler = handler;
        this.imageView = imageView;
    }

    @Override
    public void run() {
        try {
            URL httpurl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpurl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream in = conn.getInputStream();
            final Bitmap bitmap = BitmapFactory.decodeStream(in);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    imageView.setImageBitmap(bitmap);
                }
            });
            in.close();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

   具体的运行结果如下



 

猜你喜欢

转载自270827204.iteye.com/blog/2298377