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

来源:互联网 发布:java培训班 编辑:程序博客网 时间:2024/04/28 01:30

 本案例演示客户端如何解析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;}@Overridepublic void run(){URL httpUrl;try{//创建URLhttpUrl = 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(){@Overridepublic void run(){//通过调用adapter,把data传进去adapter.setData(data);listView.setAdapter(adapter);}});}}catch(MalformedURLException e){} catch (ProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.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);   //初始化}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn list.size();}@Overridepublic Object getItem(int arg0) {// TODO Auto-generated method stubreturn list.get(arg0);}@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {// TODO Auto-generated method stubHolder 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){//拿到viewname = (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 stubthis.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;}@Overridepublic void run(){//发送try {//创建URLURL 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(){@Overridepublic void run(){imageView.setImageBitmap(bitmap);}});} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
另外的三个文件Person.java、Result.java、SchoolInfo.java是实体类文件,请参阅

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

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

1 0
原创粉丝点击