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" > <TextView
android: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" /> <EditText
android: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" /> <TextView
android: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" /> <TextView
android: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" /> <TextView
android: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" /> <TextView
android: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" /> <EditText
android: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> <EditText
android: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" /> <EditText
android: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" /> <EditText
android: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" /> <Button
android: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(){ @Override
public 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; @Override
protected 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. 使用python解析Json字符串-获取Json字符串关键字

    import json data = { "statusCode": 0, "data": { ", "height": &quo ...

  2. java遍历复杂json字符串获取想要的数据

    https://blog.csdn.net/qq_34309663/article/details/80508125 java如何解析复杂的json数据关于json处理的包有好几个,比如jackson ...

  3. jquery,字符串转json对象,json对象转字符串

    字符串转json对象 方法一:var json = eval('(' + str + ')'); 方法二:return JSON.parse(str); json对象转字符串 JSON.stringi ...

  4. java 字符串解析为json 使用org.json包的JSONObject+JSONArray

    参考: https://blog.csdn.net/xingfei_work/article/details/76572550 java中四种json解析方式 JSONObject+JSONArray ...

  5. js进阶ajax读取json数据(ajax读取json和读取普通文本,和获取服务器返回数据(链接)都是一样的,在url处放上json文件的地址即可)

    js进阶ajax读取json数据(ajax读取json和读取普通文本,和获取服务器返回数据(链接)都是一样的,在url处放上json文件的地址即可) 一.总结 ajax读取json和读取普通文本,和获 ...

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

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

  7. 通过Jquery中Ajax获取json文件数据

    1. JSON(JavaScript Object Notation): javaScript对象表示法: 是存储和交换文本信息的语法,比xml更小,更快,更易解析. 2. JSON基本书写格式 : ...

  8. HttpURLConnection从网上获取Json数据并解析详解

    HttpURLConnection从网上获取Json数据并解析 1.HttpURLConnection请求数据的步骤 (1)构造一个URL接口地址: URL url = new URL("h ...

  9. Ajax获取Json多个集合并同时遍历

    Ajax获取Json多个集合并同时遍历: 方法一.:将多个集合放入MAP集合. 后台:Servlet @Override protected void doPost(HttpServletReques ...

随机推荐

  1. 指针参数的传递(节选 C++/C 高质量编程 林锐)

    指针参数是如何传递内存的 如果函数的参数是一个指针,不要指望用该指针去申请动态内存.示例7-4-1中,Test函数的语句GetMemory(str, 200)并没有使str获得期望的内存,str依旧是 ...

  2. codeforces 337C Quiz(贪心)

    转载请注明出处: http://www.cnblogs.com/fraud/          ——by fraud Quiz Manao is taking part in a quiz. The ...

  3. (原)opencv直线拟合fitLine

    转载请注明出处 http://www.cnblogs.com/darkknightzh/p/5486234.html 参考网址: http://blog.csdn.net/thefutureisour ...

  4. 图片ppm编码格式

    ppm图片有2种格式, ASCII格式和binary格式. (1)ppm头部分 由三部分组成,这三部分由回车或换行分割,但PPM的标准中是要求空格. 第一行通常是P3或P6,说明是PPM格式: 第二行 ...

  5. Win7/Win8 系统下安装Oracle 10g 提示“程序异常终止,发生未知错误”的解决方法

    我的Oracle 10g版本是10.2.0.1.0,(10.1同理)选择高级安装,提示“程序异常终止,发生未知错误”. 1.修改Oracle 10G\database\stage\prereq\db\ ...

  6. information_schema.collations 学习

    information_schema.collations 表中的每一行对应一个排序规则 1.information_schema.collations 表中学用列: 1.id :排序规则的ID 2. ...

  7. png透明图片

    2. JS处理 使用DD_belatedPNG(http://www.dillerdesign.com/experiment/DD_belatedPNG/),可以很简单的对界面上所有的透明图片进行同一 ...

  8. poj 1129 Channel Allocation

    http://poj.org/problem?id=1129 import java.util.*; import java.math.*; public class Main { public st ...

  9. Delphi线程同步(临界区、互斥、信号量,包括详细代码)

    当有多个线程的时候,经常需要去同步这些线程以访问同一个数据或资源. 例如,假设有一个程序,其中一个线程用于把文件读到内存,而另一个线程用于统计文件的字符数.当然,在整个文件调入内存之前,统计它的计数是 ...

  10. 十大面试问题解惑,秒杀一切HR、技术面试

    最能体现求职者能力的就是面试,能不能拿到Offer,取决于你面试时的表现,只有有准备才能在面试过程中游刃有余.小编收集了10个面试官最爱提的问题,虽然题目千变万化,但是万变不离其宗,只要掌握了答题的技 ...