Android中XML和JSON数据的解析小案例

一、XML
package com.itheima.ceshouji.domain;
/*
 * 
<smartresult>
	<product type="mobile">
	    <phonenum>13691689238</phonenum>
	    <location>广东深圳移动神州行卡</location>
	    <phoneJx>名虽可得,利则难获,艺界发展,可望成功 凶带吉</phoneJx>
	</product>
</smartresult>
 * 
 */
public class Product {


	private String type;
	private String phonenum;
	private String location;
	private String phoneJx;
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getPhonenum() {
		return phonenum;
	}
	public void setPhonenum(String phonenum) {
		this.phonenum = phonenum;
	}
	public String getLocation() {
		return location;
	}
	public void setLocation(String location) {
		this.location = location;
	}
	public String getPhoneJx() {
		return phoneJx;
	}
	public void setPhoneJx(String phoneJx) {
		this.phoneJx = phoneJx;
	}
	
}


public class MainActivity extends Activity {


	protected static final int SUCCESS = 0;   //成功  
	protected static final int ERROR = 1;   // 连接错误, 失败 
	EditText ed_phonenumber;
	TextView tv_result;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ed_phonenumber = (EditText) findViewById(R.id.ed_phonenumber);
		tv_result = (TextView) findViewById(R.id.tv_result);
	}
	String path;
	
	private Handler handler = new Handler(){
		
		public void handleMessage(Message msg) {
			
			switch (msg.what) {
			case SUCCESS:
				
				Product p = (Product) msg.obj;
				
				tv_result.setText(p.getPhonenum()+"\n"+p.getLocation() +"\n"+p.getPhoneJx());
				
				break;
			case ERROR:
				
				Toast.makeText(MainActivity.this, "出错了.... ", 0).show();
				System.out.println("出错了");
				break;


			default:
				break;
			}
			
			
		};
	};
	
	
	//测试 手机号码 
	public void ceyice(View v){
		
		//获得手机号码 
		String number = ed_phonenumber.getText().toString().trim();
		
		//获得 发请求的地址 
		String ip = getResources().getString(R.string.ip);
		
		//http://www.096.me/api.php?phone=13691689238&mode=xml
		path = ip+"?phone="+number+"&mode=xml";
		
//		发请求联网
		new Thread(){
			
			public void run() {
				
				try {
					URL url = new URL(path);
					
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					
					//设置请求方式
					conn.setRequestMethod("GET");
					
					//设置超时 时间 
					conn.setConnectTimeout(5000);
					
					int code = conn.getResponseCode();
					if(code==200){
						
						//服务器成功的处理了请求 
						
						InputStream in = conn.getInputStream();
						
						//由于返回的是 xml 格式的数据, 所以这里 要解析 xml 了, 使用 pull解析器 
						
						XmlPullParser parser = Xml.newPullParser();
						
						parser.setInput(in, "gbk");
/*
 * 
<?xml version="1.0" encoding="gbk"?>
<smartresult>
	<product type="mobile">
	    <phonenum>13691689238</phonenum>
	    <location>广东深圳移动神州行卡</location>
	    <phoneJx>名虽可得,利则难获,艺界发展,可望成功 凶带吉</phoneJx>
	</product>
</smartresult>
 * 						
 */
						Product p = new Product();
						int type = parser.getEventType();
						
						while(type!=XmlPullParser.END_DOCUMENT){
							
							if(type==XmlPullParser.START_TAG){
								
								if("product".equals(parser.getName())){
									String value = parser.getAttributeValue(0);
									p.setType(value);
								}else if("phonenum".equals(parser.getName())){
									String phonenum = parser.nextText();
									p.setPhonenum(phonenum);
								}else if("location".equals(parser.getName())){
									String location = parser.nextText();
									p.setLocation(location);
								}else if("phoneJx".equals(parser.getName())){
									String phoneJx = parser.nextText();
									p.setPhoneJx(phoneJx);
								}
								
							}
							type=parser.next();
						}
						
						//解析 xml 文件完成, 那么就 handler 发消息,通知 UI 界面更新 ,显示数据
						Message msg = Message.obtain();
						msg.what=SUCCESS;
						msg.obj = p;
						handler.sendMessage(msg);
						
					}
				} catch (Exception e) {
					e.printStackTrace();
					
					Message msg = Message.obtain();
					msg.what=ERROR;
					handler.sendMessage(msg);
				}
				
			};
		}.start();
		
	}
}
二、JSON
{
    "desc": "OK",
    "status": 1000,
    "data": {
        "wendu": "27",
        "ganmao": "各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。",
        "forecast": [
            {
                "fengxiang": "无持续风向",
                "fengli": "微风级",
                "high": "高温 33℃",
                "type": "阵雨",
                "low": "低温 27℃",
                "date": "26日星期三"
            },
            {
                "fengxiang": "无持续风向",
                "fengli": "微风级",
                "high": "高温 32℃",
                "type": "雷阵雨",
                "low": "低温 27℃",
                "date": "27日星期四"
            },
            {
                "fengxiang": "无持续风向",
                "fengli": "微风级",
                "high": "高温 32℃",
                "type": "雷阵雨",
                "low": "低温 26℃",
                "date": "28日星期五"
            },
            {
                "fengxiang": "无持续风向",
                "fengli": "微风级",
                "high": "高温 32℃",
                "type": "雷阵雨",
                "low": "低温 26℃",
                "date": "29日星期六"
            },
            {
                "fengxiang": "无持续风向",
                "fengli": "微风级",
                "high": "高温 31℃",
                "type": "中雨",
                "low": "低温 25℃",
                "date": "30日星期天"
            }
        ],
        "yesterday": {
            "fl": "微风",
            "fx": "无持续风向",
            "high": "高温 34℃",
            "type": "多云",
            "low": "低温 28℃",
            "date": "25日星期二"
        },
        "aqi": "67",
        "city": "深圳"
    }
}
public class MainActivity extends Activity {

	protected static final int SUCCESS = 1;
	protected static final int ERROR = 2;
	protected static final int INVALID_CITY_NAME = 3;
	EditText ed_city;
	TextView tv_day01;
	TextView tv_day02;
	TextView tv_day03;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ed_city = (EditText) findViewById(R.id.ed_city_name);
		tv_day01 = (TextView) findViewById(R.id.day01); 
		tv_day02 = (TextView) findViewById(R.id.day02); 
		tv_day03 = (TextView) findViewById(R.id.day03); 
	}
	
	Handler handler = new Handler(){
		
		public void handleMessage(android.os.Message msg) {
			
			switch (msg.what) {
			case SUCCESS:
				
				JSONArray array = (JSONArray) msg.obj;
				
				try {
					tv_day01.setText(array.getString(0));
					tv_day02.setText(array.getString(1));
					tv_day03.setText(array.getString(2));
				} catch (JSONException e) {
					e.printStackTrace();
				}
				break;
			case ERROR:
				
				//弹个土司 
				Toast.makeText(MainActivity.this, "对不起,俺出错了 .", 0).show();
				
				break;
			case INVALID_CITY_NAME:
				
				//无效的 城市 
				Toast.makeText(MainActivity.this, "无效的城市  .", 0).show();
				
				break;


			default:
				break;
			}
			
		};
		
	};
	
	String path;
	String cityname;
	//获得天气信息
	public void getWeatherInfo(View v){
		
		cityname = ed_city.getText().toString().trim();
		
		if(TextUtils.isEmpty(cityname)){
			Toast.makeText(this, "城市不能为空", 0).show();
			return;
		}
		
		//http://wthrcdn.etouch.cn/weather_mini?city=%E4%B8%8A%E6%B5%B7
		//要联网 获得 城市的天气 
		
		//深圳
		
		//怎么url 编码呢? 
		new Thread(){
			
			public void run() {
				
				try {
					String cityName = URLEncoder.encode(cityname, "UTF-8");
					
					path = "http://wthrcdn.etouch.cn/weather_mini?city="+cityName;
					
					URL url = new URL(path);
					
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					
					conn.setRequestMethod("GET");
					
					conn.setConnectTimeout(5000);
					
					int code = conn.getResponseCode();
					
					if(code==200){
						
						InputStream in = conn.getInputStream();
						
						//解析 in 数据, 这个数据是 json 格式的数据 
						//如何  将 in 的数据转换成 json格式的数据呢?
						//谷歌工程师已经将 解析json格式的api 集成 进来了, 我们只需要去用就可以了. 
						//当然, 你 也可以 ,自己去下载一些开源的json 的类库, 集成 到你的工程中, 
						
						//需要先 将流的数据 转换成一个字符串, 然后 把字符串 丢给这个json Object
						
						String value = StreamTool.decodeStream(in);
						
						JSONObject obj = new JSONObject(value);
						
						String descValue = obj.getString("desc");
						if("OK".equals(descValue)){
							
							JSONObject dataObj = obj.getJSONObject("data");
							
							//获得 预报的  json数组
							JSONArray forcastArray = dataObj.getJSONArray("forecast");
//							String vl1 = forcastArray.getString(0);
							
							Message msg = Message.obtain();
							msg.what=SUCCESS;
							msg.obj = forcastArray;
							handler.sendMessage(msg);
							
						}else{
							
							//说明城市 信息 错误 -- 无效的城市 
							System.out.println("============");
							
							Message msg = Message.obtain();
							msg.what=INVALID_CITY_NAME;  // ctrl+shift+x ---变大写 
							handler.sendMessage(msg);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					Message msg = Message.obtain();
					msg.what=ERROR;
					handler.sendMessage(msg);
				}
				
			};
		}.start();
		
		
	}
}


public class StreamTool {
	//将流解析成 字符串 
	public static String decodeStream(InputStream in) throws IOException {
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		int len = 0;
		byte[] buf = new byte[1024];
		while((len=in.read(buf))>0){
			baos.write(buf, 0, len);
		}
		
		return baos.toString();
	}
}
public class MainActivity extends Activity {

	protected static final int SUCCESS = 1;
	protected static final int ERROR = 2;
	protected static final int INVALID_CITY_NAME = 3;
	EditText ed_city;
	TextView tv_day01;
	TextView tv_day02;
	TextView tv_day03;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ed_city = (EditText) findViewById(R.id.ed_city_name);
		tv_day01 = (TextView) findViewById(R.id.day01); 
		tv_day02 = (TextView) findViewById(R.id.day02); 
		tv_day03 = (TextView) findViewById(R.id.day03); 
	}
	
	Handler handler = new Handler(){
		
		public void handleMessage(android.os.Message msg) {
			
			switch (msg.what) {
			case SUCCESS:
				
				JSONArray array = (JSONArray) msg.obj;
				
				try {
					tv_day01.setText(array.getString(0));
					tv_day02.setText(array.getString(1));
					tv_day03.setText(array.getString(2));
				} catch (JSONException e) {
					e.printStackTrace();
				}
				break;
			case ERROR:
				
				//弹个土司 
				Toast.makeText(MainActivity.this, "对不起,俺出错了 .", 0).show();
				
				break;
			case INVALID_CITY_NAME:
				
				//无效的 城市 
				Toast.makeText(MainActivity.this, "无效的城市  .", 0).show();
				
				break;


			default:
				break;
			}
			
		};
		
	};
	
	String path;
	String cityname;
	//获得天气信息
	public void getWeatherInfo(View v){
		
		cityname = ed_city.getText().toString().trim();
		
		if(TextUtils.isEmpty(cityname)){
			Toast.makeText(this, "城市不能为空", 0).show();
			return;
		}
		
		//http://wthrcdn.etouch.cn/weather_mini?city=%E4%B8%8A%E6%B5%B7
		//要联网 获得 城市的天气 
		
		//深圳
		
		//怎么url 编码呢? 
		new Thread(){
			
			public void run() {
				
				try {
					String cityName = URLEncoder.encode(cityname, "UTF-8");
					
					path = "http://wthrcdn.etouch.cn/weather_mini?city="+cityName;
					
					URL url = new URL(path);
					
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					
					conn.setRequestMethod("GET");
					
					conn.setConnectTimeout(5000);
					
					int code = conn.getResponseCode();
					
					if(code==200){
						
						InputStream in = conn.getInputStream();
						
						//解析 in 数据, 这个数据是 json 格式的数据 
						//如何  将 in 的数据转换成 json格式的数据呢?
						//谷歌工程师已经将 解析json格式的api 集成 进来了, 我们只需要去用就可以了. 
						//当然, 你 也可以 ,自己去下载一些开源的json 的类库, 集成 到你的工程中, 
						
						//需要先 将流的数据 转换成一个字符串, 然后 把字符串 丢给这个json Object
						
						String value = StreamTool.decodeStream(in);
						
						JSONObject obj = new JSONObject(value);
						
						String descValue = obj.getString("desc");
						if("OK".equals(descValue)){
							
							JSONObject dataObj = obj.getJSONObject("data");
							
							//获得 预报的  json数组
							JSONArray forcastArray = dataObj.getJSONArray("forecast");
//							String vl1 = forcastArray.getString(0);
							
							Message msg = Message.obtain();
							msg.what=SUCCESS;
							msg.obj = forcastArray;
							handler.sendMessage(msg);
							
						}else{
							
							//说明城市 信息 错误 -- 无效的城市 
							System.out.println("============");
							
							Message msg = Message.obtain();
							msg.what=INVALID_CITY_NAME;  // ctrl+shift+x ---变大写 
							handler.sendMessage(msg);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					Message msg = Message.obtain();
					msg.what=ERROR;
					handler.sendMessage(msg);
				}
				
			};
		}.start();
		
		
	}
}


public class StreamTool {
	//将流解析成 字符串 
	public static String decodeStream(InputStream in) throws IOException {
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		int len = 0;
		byte[] buf = new byte[1024];
		while((len=in.read(buf))>0){
			baos.write(buf, 0, len);
		}
		
		return baos.toString();
	}


}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值