android中的http通讯----(4)客户端解析json格式

 本案例演示客户端如何解析json格式数据,以及从服务端接收并显示文字、图片信息

项目结构:


布局文件: 

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <ListView
        android:id = "@+id/listView"
        android:layout_width="fill_parent"
		android:layout_height="fill_parent"/>
</RelativeLayout>
item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
	
 	<ImageView
        android:id="@+id/imageView"
        android:layout_alignParentLeft="true"
        android:layout_width="150dp"
        android:layout_height="100dp"/>
    <RelativeLayout
        android:padding="10dp"
        android:layout_toRightOf="@id/imageView"
        android:layout_width="fill_parent"
        android:layout_height="100dp">
        <TextView
            android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="name"/>
         <TextView
            android:layout_below="@id/name"
            android:id="@+id/age"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="age"/>
          <TextView
            android:layout_below="@id/age"
            android:id="@+id/schoolInfo1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="schoolInfo1"
            android:textSize="20sp"/>
           <TextView
            android:layout_below="@id/schoolInfo1"
            android:id="@+id/schoolInfo2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="schoolInfo2"
            android:textSize="20sp"/>
    </RelativeLayout>
</RelativeLayout>
java文件:

MainActivity.java文件

package com.example.httpjson;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ListView;

public class MainActivity extends Activity {
	private ListView listView;
    private JsonAdapter adapter;
	private Handler handler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        adapter = new JsonAdapter(this);
        String url = "http://192.168.1.118:8080";
        new HttpJson(url,listView,adapter,handler).start();
	}
	public void init(){
		listView = (ListView)findViewById(R.id.listView);
	}
}
HttpJson.java文件

package com.example.httpjson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

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

import android.content.Context;
import android.os.Handler;
import android.widget.ListView;
import android.widget.Toast;

public class HttpJson extends Thread {
	private String url;
	private ListView listView;
	private JsonAdapter adapter;
	private Handler handler;
	private Context context;	
	public HttpJson(String url,ListView listView,JsonAdapter adapter,Handler handler){
		this.url = url;
		this.listView = listView;
		this.adapter = adapter;
		this.handler = handler;
	}
	@Override
	public void run(){
		URL httpUrl;
		try{
			//创建URL
			httpUrl = new URL(url);
			//通过url拿到httpUrlConnection对象
			HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();			
			conn.setReadTimeout(5000);
			//设置请求方法
			conn.setRequestMethod("GET");
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			StringBuffer sb = new StringBuffer();
			String str;
			while((str=reader.readLine()) != null){
				sb.append(str);
				//把解析对象传进来
				final List<Person>data = parseJson(sb.toString());
				//这是一个子线程,需要往主线程发送消息
				handler.post(new Runnable(){
					@Override
					public void run(){
						//通过调用adapter,把data传进去
						adapter.setData(data);
						listView.setAdapter(adapter);
					}
				});
			}
		}catch(MalformedURLException e){
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//解析json:根据你的json格式是怎么定义,进行怎样的解析
	private List<Person> parseJson(String json){
		try{
			JSONObject object = new JSONObject(json);
			List<Person> persons = new ArrayList<Person>();
			int result = object.getInt("result");
			
			if(result == 1){//如果结果为1,没有问题,对Json对象进行解析
				//personData是一个数组
				JSONArray personData = object.getJSONArray("Person");
				
				for(int i=0; i<personData.length(); i++){
					Person personObject = new Person();
					persons.add(personObject);
					JSONObject person = personData.getJSONObject(i);
					String name = person.getString("mName");
					int age = person.getInt("mAge");
					String url = person.getString("mUrl");
				
					personObject.setAge(age);
					personObject.setName(name);
					personObject.setUrl(url);
					
					//schoolInfo也是一个数组
					JSONArray schoolInfos = person.getJSONArray("SchoolInfo");
					
					List<SchoolInfo> schInfo = new ArrayList<SchoolInfo>();
					personObject.setSchoolInfo(schInfo);
					for(int j = 0; j<schoolInfos.length(); j++){
						JSONObject school = schoolInfos.getJSONObject(i);
						String schoolName = school.getString("mSchoolName");
						SchoolInfo info = new SchoolInfo();
						info.setSchoolName(schoolName);
						schInfo.add(info);
					}					
				}
				return persons;
			}
			else{
				Toast.makeText(context,"error",1).show();
			}
		}
		catch(JSONException e)
		{
			e.printStackTrace();
		}
		return null;
	}
}
JsonAdapter.java文件:

package com.example.httpjson;
import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class JsonAdapter extends BaseAdapter {
	private List<Person>list;
	private Context context;
	private LayoutInflater inflater;		//用于触发布局
	private Handler handler = new Handler();
	
	/*构造方法*/
	public JsonAdapter(Context context,List<Person> list){
		this.context = context;
		this.list = list;
		inflater= LayoutInflater.from(context);   //初始化
	}
	public JsonAdapter(Context context){
		this.context = context;
		inflater= LayoutInflater.from(context);   //初始化
	}
	
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return list.get(arg0);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		Holder holder = null;
		if(convertView == null){
			//如果convertView为空,需要初始化item布局
			convertView = inflater.inflate(R.layout.item, null);
			holder = new Holder(convertView);
			convertView.setTag(holder);
		}
		else{
			holder = (Holder)convertView.getTag();
		}
		//拿到person对象
		Person person = list.get(position);
		//设置文本信息
		holder.name.setText(person.getName());
		//这里的age是int类型,要转换为string类型,否则会报找不到资源的错误
		holder.age.setText(""+person.getAge());
		
		List<SchoolInfo> schools = person.getSchoolInfo();
		SchoolInfo schoolInfo1 = schools.get(0);
		SchoolInfo schoolInfo2 = schools.get(1);
		
		holder.school1.setText(schoolInfo1.getSchoolName());
		holder.school2.setText(schoolInfo1.getSchoolName());
		
		//调用HttpImage方法获得图片资源
		new HttpImage(person.getUrl(),handler,holder.imageView).start();
		//把convertView返回给界面
		return convertView;
	}
	class Holder{
		private TextView name;
		private TextView age;
		private TextView school1;
		private TextView school2;
		private ImageView imageView;
		
		//构造方法
		public Holder(View view){
			//拿到view
			name = (TextView)view.findViewById(R.id.name);
			age = (TextView)view.findViewById(R.id.age);
			school1 = (TextView)view.findViewById(R.id.schoolInfo1);
			school2 = (TextView)view.findViewById(R.id.schoolInfo2);
			imageView = (ImageView)view.findViewById(R.id.imageView);
		}
	}
	//创建公用方法
	public void setData(List<Person> data) {
		// TODO Auto-generated method stub
		this.list =data;
	}	
}
HttpImage.java

package com.example.httpjson;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.widget.ImageView;
public class HttpImage extends Thread{
	private ImageView imageView;
	private String url;
	
	private Handler handler;
	public HttpImage(String url,Handler handler,ImageView imageView){
		this.url = url;
		this.handler = handler;
		this.imageView = imageView;
	}
	
	@Override
	public void run(){
		//发送
		try {
			//创建URL
			URL httpUrl = new URL(url);
			//通过url拿到httpUrlConnection对象
			HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();			
			conn.setReadTimeout(5000);
			//设置请求方法
			conn.setRequestMethod("GET");
			//拿到输入流对象
			InputStream in = conn.getInputStream();
			final Bitmap bitmap = BitmapFactory.decodeStream(in);
			
			handler.post(new Runnable(){
				@Override
				public void run(){
					imageView.setImageBitmap(bitmap);
				}
			});
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
}
另外的三个文件Person.java、Result.java、SchoolInfo.java是实体类文件,请参阅

http://blog.csdn.net/baoxiaofeicsdn/article/details/49906147

//重要说明:main_activity.java文件中url对应的服务器中存储了学生信息,这里地址没有给全,需自行给定另外的服务器地址        

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值