Json获取、解析案例演示----xml解析

页面导航:首页 > 网络编程 > JavaScript > Json获取、解析案例演示----xml解析

Json获取、解析案例演示----xml解析

来源: 作者: 时间:2016-01-19 18:32 【

JSON有两种表示结构,对象和数组 对象结构以{大括号开始,以}大括号结束。中间部分由0或多个以,分隔的key(关键字) value(值)对构成,关键字和值之间以:分隔,语法结构如代码。其中

JSON有两种表示结构,对象和数组.

对象结构以”{”大括号开始,以”}”大括号结束。中间部分由0或多个以”,”分隔的”key(关键字)/value(值)”对构成,关键字和值之间以”:”分隔,语法结构如代码。

其中关键字是字符串,而值可以是字符串,数值,true,false,null,对象或数组

数组结构以”[”开始,”]”结束。中间由0或多个以”,”分隔的值列表组成,语法结构如代码。

****************************************************案例*******************************************

这里先贴出bean类

Result

 

package com.lw.bean;

import java.util.ArrayList;
import java.util.List;

public class Result {
	//结果值,如果为2说明返回正确
	private int result;
	private List personData =  new ArrayList();
	public int getResult() {
		return result;
	}
	public void setResult(int result) {
		this.result = result;
	}
	public List getPersonData() {
		return personData;
	}
	public void setPersonData(List personData) {
		this.personData = personData;
	}
	
	
}
Person

 

 

package com.lw.bean;

import java.util.List;

public class Person {
	private String url;
	private String name;
	private int age;
	private List schoolInfo;


	public List getSchoolInfo() {
		return schoolInfo;
	}

	public void setSchoolInfo(List schoolInfo) {
		this.schoolInfo = schoolInfo;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}
}

SchoolInfo

 

 

package com.lw.bean;

public class SchoolInfo {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
接下来贴出主界面布局和Listview中的每个item的布局文件

 

json.xml

 

 


    


item.xml

 

 

 


    

    

        

        

        

        
    



接下来贴出主activity

 

JsonActivyty

 

package com.lw.http01;

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

public class JsonActivyty extends Activity {

	private ListView listView;
	private JsonAdapter jsonAdapter;
	private Handler handler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		/** json布局文件中,只有一个listview控件 */
		setContentView(R.layout.json);
		listView = (ListView) findViewById(R.id.listView);
		/**
		 * 一开始是没有数据的,后来从服务器获取在子线程中跟新数据和ui界面的
		 * 
		 */
		jsonAdapter = new JsonAdapter(this);
		
		/**
		 * 服务度http://192.168.79.101:8080/testServer/jsonServlet就能获取到json数据
		 * 这里没有贴出服务端代码,知道上面一句话就够了
		 */
		new JsonThread(
				http://192.168.79.101:8080/testAndroidServer/jsonServlet,
				this, listView, jsonAdapter, handler).start();
	}
}

接下来循序渐进先贴出

 

JsonThread

 

package com.lw.http01;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
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;

import com.lw.bean.Person;
import com.lw.bean.SchoolInfo;

public class JsonThread extends Thread {

	/**
	 * url是服务器地址
	 * context是环境,需要toast提示
	 * listview是需要setadapter的设置适配器
	 * jsonAdapter是需要设置数据的
	 * handler是需要子线程更新ui的
	 */
	private String url;
	private Context context;
	private ListView listView;
	private JsonAdapter jsonAdapter;
	private Handler handler;

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

	@Override
	public void run() {
		try {
			// 创建URL对象,并且设置相应的参数
			URL httpurl = new URL(url);
			//打开连接
			HttpURLConnection conn = (HttpURLConnection) httpurl
					.openConnection();
			conn.setReadTimeout(5000);
			conn.setRequestMethod(GET);

			// 从服务器读取数据,需要读入流
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));

			// 读取完毕,就存放到StringBuffer容器中
			StringBuffer sb = new StringBuffer();
			String str = ;
			while ((str = reader.readLine()) != null) {
				// 当读取完毕,就添加到容器中
				sb.append(str);
			}
			// 将读取到的Json字符串,进行解析为Person对象集合
			final List parseJson = parseJson(sb.toString());
			// handler在子线程中更新数据
			handler.post(new Runnable() {

				@Override
				public void run() {
					// 设置数据到adapter视图中,使其获取到数据
					jsonAdapter.setData(parseJson);
					// 设置适配器
					listView.setAdapter(jsonAdapter);
				}
			});

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

	/***
	 * 解析服务端返回的Json字符串数据,因为adapter的视图中item是一个个Person对象,所以返回Person集合即可
	 * 这里用android的原生解析
	 */
	private List parseJson(String json) {
		//json解析完毕,返回person的集合对象
		List persons = new ArrayList();
		try {
			/**
			 * {1:[{person对象},{person对象},{person对象}]}
			 * 所以整体是个json对象,而不是json数组
			 * 所以创建JSONObject对象
			 */
			
			JSONObject jsonObj = new JSONObject(json);
			//获取result值
			int result = jsonObj.getInt(result);

			//如果为2说明返回正确
			if (result == 2) {
				//获取person的json数组
				JSONArray personData = jsonObj.getJSONArray(personData);

				/**
				 * 循环解析每一个person对象
				 */
				for (int i = 0; i < personData.length(); i++) {
					//创建person对象
					Person personObj = new Person();
					List scInfos = new ArrayList();

					//从json对象数组中获取每一个json类型的person对象
					JSONObject person = personData.getJSONObject(i);
					//为person对象设置json类型的person对象的值
					personObj.setName(person.getString(name));
					personObj.setAge(person.getInt(age));
					personObj.setUrl(person.getString(url));


					/**获取json类型的person中的school信息*/
					JSONArray scs = person.getJSONArray(schoolInfo);
					for (int j = 0; j < scs.length(); j++) {
						SchoolInfo schoolObj = new SchoolInfo();
						JSONObject school = scs.getJSONObject(j);
						schoolObj.setName(school.getString(name));
						scInfos.add(schoolObj);
					}

					personObj.setSchoolInfo(scInfos);
					persons.add(personObj);

				}
			} else {
				Toast.makeText(context, error, 1);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return persons;
	}

}


接下来贴出适配器的代码

 

JsonAdapter

 

package com.lw.http01;

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;

import com.lw.bean.Person;
import com.lw.bean.SchoolInfo;

public class JsonAdapter extends BaseAdapter {

	private List list;
	private Context context;
	private LayoutInflater inflater;
	private Handler handler = new Handler();
	
	public JsonAdapter(Context context) {
		this.context = context;
		inflater = LayoutInflater.from(context);
	}

	public JsonAdapter(List list, Context context) {
		this.list = list;
		this.context = context;
		inflater = LayoutInflater.from(context);
	}
	/**
	 * 设置数据的,数据是从服务器解析过来的
	 * @param list
	 */
	public void setData(List list){
		this.list = list;
	}

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

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

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

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.item, null);
			holder = new ViewHolder(convertView);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		/***
		 * item的数据是从setData中得来的,是jsonThread中handler操作的
		 */
		Person person = list.get(position);
		holder.name.setText(person.getName());
		holder.age.setText(person.getAge()+);

		List scs = person.getSchoolInfo();
		holder.school1.setText(scs.get(0).getName());
		holder.school2.setText(scs.get(1).getName());
		//这里的图片信息,也是需要开启子线程,进行获取,需要传递这3个参数
		new HttpImage(holder.imageView, person.getUrl(), handler).start();
		return convertView;
	}

	/**
	 * viewHodler不解释
	 *
	 */
	class ViewHolder {
		private TextView name;
		private TextView age;
		private TextView school1;
		private TextView school2;
		private ImageView imageView;

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

接下来图片获取的线程

 

HttpImage

 

package com.lw.http01;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
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 {
	/**
	 * imageview是需要在分线程中handler更新ui的
	 * url是图片的url
	 * handler是子线程跟新ui操作的
	 */
	private ImageView imageView;
	private String url;
	private Handler handler;

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

	@Override
	public void run() {
		try {
			/**
			 * 跟jsonThread操作一样,系列的参数
			 */
			URL httpurl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) httpurl.openConnection();
			conn.setReadTimeout(5000);
			conn.setRequestMethod(GET);
			//这样的方式也可以获取一个图片  decodeStream
			final Bitmap bitmap = BitmapFactory.decodeStream(conn.getInputStream());
			
			handler.post(new Runnable() {
				
				@Override
				public void run() {
					//子线程中直接更新界面
					imageView.setImageBitmap(bitmap);
				}
			});
			
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	

}

***************************************************xml解析**************************************

xml_activity.xml 里面是有一个TextView

Girl

 

package com.lw.bean;

public class Girl {
	private String name;
	private int age;
	private String school;

	@Override
	public String toString() {
		return Girl [name= + name + , age= + age + , school= + school
				+ ];
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getSchool() {
		return school;
	}

	public void setSchool(String school) {
		this.school = school;
	}

}

XmlActivity

 

 

package com.lw.http01;

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

public class XmlActivity extends Activity {
	private TextView textView;
	private Handler handler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xml_activity);
		textView = (TextView) findViewById(R.id.textView);

		String url = 服务器地址;
		new XmlThread(url, textView, handler).start();
	}

}

XmlThread

 

 

package com.lw.http01;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.os.Handler;
import android.widget.TextView;

import com.lw.bean.Girl;

public class XmlThread extends Thread {

	private String url;
	private TextView textView;
	private Handler handler;

	public XmlThread(String url, TextView textView, Handler handler) {
		super();
		this.url = url;
		this.textView = textView;
		this.handler = handler;
	}

	@Override
	public void run() {
		super.run();
		try {
			URL httpUrl = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) httpUrl
					.openConnection();
			connection.setReadTimeout(5000);
			connection.setRequestMethod(GET);
			InputStream in = connection.getInputStream();
			// 解析工厂类
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			XmlPullParser parser = factory.newPullParser();
			parser.setInput(in, UTF-8);

			final List list = new ArrayList();
			Girl girl = null;

			int eventType = parser.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT) {
				String data = parser.getName();
				switch (eventType) {
				case XmlPullParser.START_TAG:
					if (girl.equals(data)) {
						girl = new Girl();
					}
					if (name.equals(data)) {
						girl.setName(parser.nextText());
					}
					if (age.equals(data)) {
						girl.setAge(Integer.parseInt(parser.nextText()));
					}
					if (school.equals(data)) {
						girl.setSchool(parser.nextText());
					}
					break;
				case XmlPullParser.END_TAG:
					if (girl.equals(data) && girl != null) {
						list.add(girl);

					}
					break;
				}
				eventType = parser.next();
			}
			handler.post(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					textView.setText(list.toString());
				}
			});
		} catch (Exception e) {
		}
	}

}


 

Tags:

文章评论

最 近 更 新
热 点 排 行
Js与CSS工具
代码转换工具

<