Android之解析json数据

本文介绍了一种通过HTTP请求获取并解析JSON格式天气数据的方法,包括实现步骤与具体代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载请注明出处:http://blog.youkuaiyun.com/joker_ya/article/details/39584327

最近比较忙,没什么时间写文章了。今天刚好有空,所以就打算写一篇关于解析json数据的文章。解析json数据的方法有很多,这里就给读者带来一种最简单的方法。好吧,首先我们要有数据源。没有数据还谈什么解析嘛。笔者在网上找了一个跟天气相关的API接口。用于得到某一城市的天气的json数据作为数据源。例如:http://www.weather.com.cn/data/sk/101010100.html   数字101010100的是北京的城市代码,因此该地址返回的是北京市的天气的json数据。如果读者想查看其它城市的天气,可以百度读者想要查看的城市的天气城市代码,将那组数字换掉即可得到相应的数据了。打开上面的链接结果如下:

可以看到返回的确实是json数据。那么,接下来就一起编写写一个应用来显示这段数据。


新建名为WeatherDemo的工程,目录如下:


主界面布局activity_main.xml很简单,就一个Button和一些TextView、Edittext:

<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity" >

    <Button 
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="获取天气"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="城市名称:" />

    <EditText
        android:id="@+id/tx_cityname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" />   

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="城市ID:" />

    <EditText
        android:id="@+id/tx_cityid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" />   
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="当地时间:" />

    <EditText
        android:id="@+id/tx_time"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" />   

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="城市温度:" />

    <EditText
        android:id="@+id/tx_temp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" />
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="风向:" />

    <EditText
        android:id="@+id/tx_WD"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="风强度:" />

    <EditText
        android:id="@+id/tx_WS"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" />

</LinearLayout>

然后就是GetWeatherInfo.java了,该类主要作用是得到json数据并对其解析,然后返回。

package com.example.weatherdemo;

import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

/**
 * 得到天气信息
 * 
 * @author Joker_Ya
 * 
 */
public class GetWeatherInfo {

	/**
	 * 根据URL打开链接,并对数据进行解析,然后返回数据
	 * 
	 * @param path
	 *            url地址
	 * @return
	 * @throws Exception
	 */
	public static HashMap<String, String> getInfo(String path) throws Exception {
		// 得到HttpGet实例
		HttpGet get = new HttpGet(path);
		// 得到HttpClient
		HttpClient client = new DefaultHttpClient();
		// 请求方式为get
		HttpResponse response = client.execute(get);
		String strResult = "";// 用于存放json数据
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 判断请求是否成功
			strResult = EntityUtils.toString(response.getEntity());
			// 得到JSONObject对象,该对象可以根据key得到相应的数据
			JSONObject object = new JSONObject(strResult)
					.getJSONObject("weatherinfo");

			HashMap<String, String> data = new HashMap<String, String>();

			String cityname = object.getString("city");
			String cityid = object.getString("cityid");
			String time = object.getString("time");
			String temp = object.getString("temp");
			String WD = object.getString("WD");
			String WS = object.getString("WS");

			data.put("cityname", cityname);
			data.put("cityid", cityid);
			data.put("time", time);
			data.put("temp", temp);
			data.put("WD", WD);
			data.put("WS", WS);
			return data;
		}
		return null;
	}
}


最后附上MainActivity.java。主要是显示数据,需要注意还是那个:不能再主线程里访问网络,否则会报错。因此得新开一条线程来访问网络得到数据。

package com.example.weatherdemo;

import java.util.HashMap;

import com.example.weatherbyjson.R;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * 获取某一城市的天气信息
 * @author Joker_Ya
 * 
 */
public class MainActivity extends Activity {

	private final static int SUCCESS = 1;// 获取天气信息标识
	private final static int FAIL = 2;// 获取天气是不标识

	private Button mButton;
	private EditText cityname;
	private EditText cityid;
	private EditText time;
	private EditText temp;
	private EditText WD;
	private EditText WS;
	// 获取天气信息地址
	private String urlStr = "http://www.weather.com.cn/data/sk/101010100.html";
	// data用于存放天气相关的信息
	private HashMap<String, String> data = null;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case SUCCESS:
				// 显示数据
				cityname.setText(data.get("cityname"));
				cityid.setText(data.get("cityid"));
				time.setText(data.get("time"));
				temp.setText(data.get("temp"));
				WD.setText(data.get("WD"));
				WS.setText(data.get("WS"));
				break;
			case FAIL:
				Toast.makeText(MainActivity.this, "fail", 3000).show();
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 根据id得到控件
		mButton = (Button) findViewById(R.id.button);
		cityname = (EditText) findViewById(R.id.tx_cityname);
		cityid = (EditText) findViewById(R.id.tx_cityid);
		time = (EditText) findViewById(R.id.tx_time);
		temp = (EditText) findViewById(R.id.tx_temp);
		WD = (EditText) findViewById(R.id.tx_WD);
		WS = (EditText) findViewById(R.id.tx_WS);
		// 添加按钮的点击事件
		mButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 启动线程
				new Thread(myRunable).start();
			}
		});

	}

	// new一个myRunable
	Runnable myRunable = new Runnable() {
		public void run() {
			try {
				// 调用GetWeatherInfo中的getInfo()方法将返回的数据存入到data中
				data = GetWeatherInfo.getInfo(urlStr);
				// 发送消息
				handler.sendEmptyMessage(SUCCESS);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				handler.sendEmptyMessage(FAIL);
			}
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

还有就是别忘了在清单文件里加入访问网络的权限。

<uses-permission android:name="android.permission.INTERNET"/>


好了,应用写完了。接下来就运行查看结果了。

    



ok!我们已经完成了对天气信息的显示了。有没有很简单哩!


最后附上源码下载地址:

源码下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值