androidの获取天气预报JSON 实现

androidの获取天气预报JSON 实现
1.  首先推荐json格式检查工具
     http://www.bejson.com/
     有效查询该json 格式是否合法
2. JSON中两种结构:对象和数组
1)、对象:对象在js中表示为“{}”括起来的内容,数据结构为  {key:value,key:value,…} 的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,所以很容易理解,取值方法为 对象.key 获取属性值,这个属性值的类型可以是 数字、字符串、数组、对象几种。

2)、数组:数组在js中是中括号“[]”括起来的内容,数据结构为 [“java”,“javascript”,“vb”,…],取值方式和所有语言中一样,使用索引获取,字段值的类型可以是 数字、字符串、数组、对象几种。

3. JSON不同格式解析
(1)json对象格式1
{"name":"sam","age":18,"weight":60}
 即为
{
    "name": "sam",
    "age": 18,
    "weight": 60
}
解析方法:
JSONObject jsonObj;
try {
    jsonObj = new JSONObject(str);
    String name = jsonObj.optString("name");
    int age = jsonObj.optInt("age");
    int weight = jsonObj.optInt("weight");
} catch (JSONException e) {
    e.printStackTrace();
(2) JSON对象格式2
{"weatherinfo":{"city":"北京","cityid":"101010100","temp":"9","WD":"西南风",
        "WS":"2级","SD":"22%","WSE":"2","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1014","time":"10:45"}}
即为
{
    "weatherinfo": {
        "city": "北京",
        "cityid": "101010100",
        "temp": "9",
        "WD": "西南风",
        "WS": "2级",
        "SD": "22%",
        "WSE": "2",
        "isRadar": "1",
        "Radar": "JC_RADAR_AZ9010_JB",
        "njd": "暂无实况",
        "qy": "1014",
        "time": "10:45"
    }
}
解析方法:
JSONObject jsonObj;
try {
jsonObj = new JSONObject(str).getJSONObject("weatherinfo");
int tmp = jsonObj.optInt("temp");
String city=jsonObj.optString("city");
} catch (JSONException e) {
e.printStackTrace();
}
(3)JSON 数组格式
[12,13,15]                     //json2 一个数字数组
解析方法
JSONArray jsonArray;
try {
jsonArray = new JSONArray(str);
for (int i= 0; i < jsonArray.length();i++) {
    int age = jsonArray.optInt(i);
}
} catch (JSONException e) {
    e.printStackTrace();
}
(4)JSON复杂数据格式
[{ "name" : "sam" , "age" :18},{ "name" : "leo" , "age" :19},{ "name" : "sky" "age" :20}]
即为
[
    {
        "name": "sam",
        "age": 18
    },
    {
        "name": "leo",
        "age": 19
    },
    {
        "name": "sky",
        "age": 20
    }
]
解析方法:
JSONArray jsonArray;
try {
jsonArray = new JSONArray(str);
for (int i= 0; i < jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
String name = jsonObject.optString("name");
int age = jsonObject.optInt("age");
}
} catch (JSONException e) {
	e.printStackTrace();
}







获取当天天气状况利用json实现,如图
 
  从网络端获取的json格式为:
{"city":"上海","date":"周一 02月02日 (实时:6℃)","dayPictureUrl":"http://api.map.baidu.com/images/weather/day/xiaoyu.png","nightPictureUrl":"http://api.map.baidu.com/images/weather/night/xiaoyu.png","temperature":"8 ~ 5℃","weather":"小雨","wind":"东北风微风"}

2. 具体代码实现
首先想到是利用线程执行网络访问,否则会出错的。
private void updateTodayWea() {
	new Thread() {
		@Override
		public void run() {
				super.run();
				String str = Constants.server + ":8080/beastat/"+ "todaywea.jsp";
				strjson = Httputils.connServerForResult(str);
				if (strjson != null) {
					Message message = new Message();
					message.what = 0;
					handler.sendMessage(message);
				} else {
					Toast.makeText(MainActivity.this, "返回为空", 1000).show();
				}
			}
		}.start();
	}
利用Handler 处理,发送消息过去。
但是,我们要获取url ,Httputils.connServerForResult(str); 返回json数据内容。
// 参数strUrl
	public static String connServerForResult(String strUrl) {
		// HttpGet对象
		HttpGet httpRequest = new HttpGet(strUrl);
		String strResult = "";
		try {
			// HttpClient对象
			HttpClient httpClient = new DefaultHttpClient();
			// 获得HttpResponse对象
			HttpResponse httpResponse = httpClient.execute(httpRequest);
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 取得返回的数据
				strResult = EntityUtils.toString(httpResponse.getEntity());
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return strResult;
	}
通过get 获取网络端数据,然后解析
以下是解析普通json数据过程。
// 普通Json数据解析
	private void parseJson(String strResult) {
		try {
			JSONObject jsonObj = new JSONObject(strResult);
			String city = jsonObj.getString("city");
			String date = jsonObj.getString("date");
			String temperature = jsonObj.getString("temperature");
			String weather = jsonObj.getString("weather");
			String wind = jsonObj.getString("wind");
			textview.setText("城市:" + city + "    时间:" + date + "\n天气:"
					+ weather + "     风:" + wind + "  温度:" + temperature);
		} catch (JSONException e) {
			System.out.println("Json parse error");
			e.printStackTrace();
		}
	}


  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android中,获取天气信息的一种常见方法是使用JSON格式的数据。JSON(JavaScript对象表示法)是一种轻量级的数据交换格式,可以将数据转换成易读和易解析的字符串格式。以下是如何获取天气信息的步骤: 1.获取天气数据的JSON源文件。可以通过使用一个API(应用程序编程接口)来获取天气数据的JSON源文件。许多API提供免费的开放访问,可以在无需进行任何身份验证的情况下访问数据。一些流行的API包括OpenWeatherMap和Yahoo!天气。 2.使用URL读取获取JSON数据。可以使用HttpURLConnection或第三方库如Volley来获取指定URL的JSON数据。例如,如果使用OpenWeatherMap API,可以使用以下代码获取JSON数据: URL url = new URL("http://api.openweathermap.org/data/2.5/weather?q=London&appid={API_KEY}"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String data = reader.readLine(); connection.disconnect(); 3.解析JSON数据。可以使用JSON解析库来解析JSON数据,例如Gson或Jackson。以下是使用Gson解析JSON数据的示例代码: Gson gson = new Gson(); WeatherData weatherData = gson.fromJson(data, WeatherData.class); 4.使用解析后的数据更新应用程序的界面。可以使用解析后的数据来更新应用程序的界面,例如在TextView中显示温度和天气概况。以下是一个使用解析后的数据更新TextView的示例代码: TextView temperatureTextView = findViewById(R.id.temperature_text_view); temperatureTextView.setText(weatherData.getMain().getTemp() + " ℃"); 总之,获取天气信息的JSON数据是Android开发中的一项常见任务。可以使用开源JSON解析库和第三方API轻松地获取、解析和使用这些数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值