google提供了天气的api,以广州天气为例,地址为:

http://api.openweathermap.org/data/2.5/weather?q=guangzhou

返回的结果为:

{
"coord": {
"lon": 113.25,
"lat": 23.12
},
"sys": {
"message": 0.2088,
"country": "CN",
"sunrise": 1400017567,
"sunset": 1400065233
},
"weather": [
{
"id": 501,
"main": "Rain",
"description": "moderate rain",
"icon": "10d"
}
],
"base": "cmc stations",
"main": {
"temp": 299.818,
"temp_min": 299.818,
"temp_max": 299.818,
"pressure": 1004.54,
"sea_level": 1014.72,
"grnd_level": 1004.54,
"humidity": 97
},
"wind": {
"speed": 4.42,
"deg": 201.501
},
"rain": {
"3h": 6
},
"clouds": {
"all": 44
},
"dt": 1400055192,
"id": 1809858,
"name": "Guangzhou",
"cod": 200
}

因此,在本范例中,写一个天气查询的DEMO,用于输入地点,并查询天气情况。

项目更新请见:https://code.csdn.net/jediael_lu/googleweatherparse/tree/master

效果如下:

详细步骤如下:

1、主界面布局文件

<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" ><TextViewandroid:id="@+id/textView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_alignParentTop="true"android:layout_marginTop="15dp"android:text="@string/location"android:textAppearance="?android:attr/textAppearanceMedium" /><EditTextandroid:id="@+id/editText1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBottom="@+id/textView1"android:layout_alignParentRight="true"android:ems="10" /><TextViewandroid:id="@+id/textView2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/textView1"android:layout_below="@+id/textView1"android:layout_marginTop="68dp"android:text="@string/country"android:textAppearance="?android:attr/textAppearanceSmall" /><TextViewandroid:id="@+id/textView3"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/textView2"android:layout_marginTop="19dp"android:text="@string/temperature"android:textAppearance="?android:attr/textAppearanceSmall" /><TextViewandroid:id="@+id/textView4"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/textView3"android:layout_below="@+id/textView3"android:layout_marginTop="32dp"android:text="@string/humidity"android:textAppearance="?android:attr/textAppearanceSmall" /><TextViewandroid:id="@+id/textView5"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/textView4"android:layout_below="@+id/textView4"android:layout_marginTop="21dp"android:text="@string/pressure"android:textAppearance="?android:attr/textAppearanceSmall" /><EditTextandroid:id="@+id/editText2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_above="@+id/textView3"android:layout_toRightOf="@+id/textView3"android:ems="10" ><requestFocus /></EditText><EditTextandroid:id="@+id/editText3"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBaseline="@+id/textView3"android:layout_alignBottom="@+id/textView3"android:layout_alignLeft="@+id/editText2"android:ems="10" /><EditTextandroid:id="@+id/editText4"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_above="@+id/textView5"android:layout_alignLeft="@+id/editText1"android:ems="10" /><EditTextandroid:id="@+id/editText5"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBaseline="@+id/textView5"android:layout_alignBottom="@+id/textView5"android:layout_alignRight="@+id/editText4"android:ems="10" /><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/editText2"android:layout_below="@+id/editText1"android:onClick="open"android:text="@string/weather" /></RelativeLayout>

2、定义String.xml

<?xml version="1.0" encoding="utf-8"?>
<resources><string name="app_name">JSONParser</string><string name="action_settings">Settings</string><string name="hello_world">Hello world!</string><string name="location">Location</string><string name="country">Country:</string><string name="temperature">Temperature:</string><string name="humidity">Humidity:</string><string name="pressure">Pressure:</string><string name="weather">Weather</string>
</resources>

3、在AndroidManifest.xml中添加internet访问权限。

4、创建一个bean,用于保存天气信息。

package com.example.jsonparser.model;public class WeatherBean {private String country;private int Temperature;private int humidity;private int pressure;public String getCountry() {return country;}public void setCountry(String country) {this.country = country;}public int getTemperature() {return Temperature;}public void setTemperature(int temperature) {Temperature = temperature;}public int getHumidity() {return humidity;}public void setHumidity(int humidity) {this.humidity = humidity;}public int getPressure() {return pressure;}public void setPressure(int pressure) {this.pressure = pressure;}}

5、创建用于访问网络的类,并返回JSON文本。

package com.example.jsonparser;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;public class JSONFetcher {private String jsonText = "";//本方法通过指定url访问网络数据,并返回JSON格式的string。public  String getJSONText(final URL url){Thread thread = new Thread(new Runnable(){@Overridepublic void run() {InputStream is =null;BufferedReader in = null;try {HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(10000 /* milliseconds */);conn.setConnectTimeout(15000 /* milliseconds */);conn.setRequestMethod("GET");conn.setDoInput(true);conn.connect();is = conn.getInputStream();in = new BufferedReader(new InputStreamReader(is));String line = "";while((line = in.readLine()) != null){jsonText += line;}} catch (IOException e) {e.printStackTrace();}finally{try {in.close();is.close();} catch (IOException e) {e.printStackTrace();}}}});thread.start();   //等待上述线程完成执行后再返回jsonText。try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}return jsonText;}}

6、创建用于处理JSON文本的类,返回一个WeatherBean对象。

package com.example.jsonparser;import java.net.URL;import org.json.JSONException;
import org.json.JSONObject;import com.example.jsonparser.model.WeatherBean;public class JSONUtil {public static WeatherBean getWeatherBean(URL url){String jsonText = new JSONFetcher().getJSONText(url);System.out.println(jsonText);WeatherBean weather = new WeatherBean();try {JSONObject weatherJSONObject = new JSONObject(jsonText);JSONObject sysJSONObject = weatherJSONObject.getJSONObject("sys");String country = sysJSONObject.getString("country");JSONObject mainJSONObject = weatherJSONObject.getJSONObject("main");int temperature = mainJSONObject.getInt("temp");int pressure = mainJSONObject.getInt("pressure");int humidity = mainJSONObject.getInt("humidity");weather.setCountry(country);weather.setTemperature(temperature);weather.setHumidity(humidity);weather.setPressure(pressure);} catch (JSONException e) {System.out.println("test");e.printStackTrace();}return weather;}
}

7、主布局文件,将WeatherBean中的内容在手机中展现。

package com.example.jsonparser;import java.net.URL;import com.example.jsonparser.model.WeatherBean;import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;public class MainActivity extends Activity {private String url1 = "http://api.openweathermap.org/data/2.5/weather?q=";private EditText location, country, temperature, humidity, pressure;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);location = (EditText) findViewById(R.id.editText1);country = (EditText) findViewById(R.id.editText2);temperature = (EditText) findViewById(R.id.editText3);humidity = (EditText) findViewById(R.id.editText4);pressure = (EditText) findViewById(R.id.editText5);}public void open(View view) {try {URL url = new URL(url1 + location.getText().toString());System.out.println(url);WeatherBean weatherBean = JSONUtil.getWeatherBean(url);country.setText(weatherBean.getCountry());humidity.setText(weatherBean.getHumidity() + "");pressure.setText(weatherBean.getPressure() + "");temperature.setText(weatherBean.getTemperature() + "");System.out.println("test2");} catch (Exception e) {e.printStackTrace();}}
}

JSON之三:获取JSON文本并解释(以google的天气API为例)相关推荐

  1. js解析json js获取json里面的某个节点的数据 js解析json数据

    获取data里面的节点 $.ajax({type: "GET",url: '../api/数据接口.aspx',dataType: 'json',success: function ...

  2. java:字符串转json并获取json值

    假设有一串字符串的值是 "user: {"code":"ceshiadd","name":"ceshiadd" ...

  3. c语言 json数组长度,js 获取json数组里面数组的长度

    作为一个前端页面开发者第一次处理json数据,遇到了'js 获取json数组里面数组的长度'?竟然不知道 json没有.length属性(真是要嘲讽下自己),少壮不努力老大徒伤悲啊!以前都是去寻求男朋 ...

  4. html代码放进json数据,用json数据填充html表

    好的,在这个解决方案中,我假设您的外部json文件名为'example.json' 你的外部文件应该是这样的 示例.json: [ { "COUNTRY":"UK&quo ...

  5. 富文本编辑器--获取JSON

    获取 JSON 格式的内容 可以通过editor.txt.getJSON获取 JSON 格式的编辑器的内容,v3.0.14开始支持,示例如下 <div id="div1"&g ...

  6. java $.getjson_JQuery 获取json数据$.getJSON方法的实例代码

    jQuery系列 第八章 jQuery框架Ajax模块 第八章 jQuery框架Ajax模块 8.1 jQuery框架中的Ajax简介 Ajax技术的核心是XMLHTTPRequest对象,该对象是A ...

  7. ajax中json和文本的区别,json格式字符串--json对象 【ajax_responseText】重点

    JSON.parse(string) JSON.Stringify(object)document.getElementById("id").value=jsonObj    // ...

  8. datagrid php json,thinkphp和easyui结合中,datagrid等容器获取json数据的方法

    一直使用两者进行前后台开发,非常方便,但在datagrid中获取json数据并显示的时候碰到了问题,网上资料非常的少,基本都是jsp和php的,thinkphp框架的就没有了,可能非常简单,但本人刚学 ...

  9. highcharts ajax 数据格式,Highcharts ajax获取json对象动态生成报表生成 .

    最近做个项目,项目经理想做一个统计报表,在网上查看些资料就选用Highchars 这里和大家分享下使用心得. 重点说明此代码是针对一个报表显示多个项对比显示. 直接贴代码:web端 $(documen ...

最新文章

  1. python小技巧及速度提高-python编码时有什么技巧可以提升速度?
  2. Android 5.0 Lollipop介绍
  3. 基于GRU和am-softmax的句子相似度模型 | 附代码实现
  4. 春招快到了,送你一份数据分析常见面试题
  5. OpenCV4.0-alpha发布!新增多个深度学习特性
  6. Java基础---循环结构+例题
  7. 玩转华为云开发|老板万万没想到:刚入职的我一人就搞定人脸识别开发
  8. 部署模型之Libtorch学习(一)
  9. 【Java架构:基础技术】一篇文章搞掂:MySQL
  10. 工信部:中国4G用户量已居世界首位
  11. javascript---不可靠的“undefined”
  12. python如何输入n个数字_python如何一次性输入多个数
  13. spark3.0-spark入门-总结知识要点
  14. 安装在ntfs分区的linux,从硬盘NTFS分区安装mandriva linux
  15. Unity5.3官方VR教程重磅登场-系列4 VR中的用户界面
  16. 两台笔记本一台连接不上wifi
  17. [网络安全自学篇] 七十六.逆向分析之OllyDbg动态调试工具(二)INT3断点、反调试、硬件断点与内存断点
  18. Linux2.6.29设备模型分析-概述
  19. 3dmax 创建圆锥体1
  20. 新世纪的群众性幻想与癫狂3

热门文章

  1. 14行代码AC_Break the Chocolate HDU-4112(数学推导+解析)
  2. 解题报告——蓝桥 试题 基础练习 矩阵乘法——27行代码AC
  3. 辽宁交通高等专科学校有计算机专业吗,辽宁省交通高等专科学校可以转专业吗,辽宁省交通高等专科学校新生转专业政策...
  4. 将项目依赖也打到jar包中
  5. OpenStack的部署T版(八)——Dashboard
  6. 索尼笔记本如何进Bios设置U盘启动
  7. 返回包禁止返回server_kubernetes部署metrics-server
  8. docker启动后自动退出_Spring Boot项目启动后如何自动执行逻辑
  9. python数组plot_Python Matplotlib:动态更新plot-数组长度未知
  10. 华为鸿蒙发布会新手机,曝华为 P50/Pro 系列最终版确定,6 月 2 日揭晓鸿蒙手机发布时间...