JSON之三:获取JSON文本并解释(以google的天气API为例)
google提供了天气的api,以广州天气为例,地址为:
http://api.openweathermap.org/data/2.5/weather?q=guangzhou
返回的结果为:
因此,在本范例中,写一个天气查询的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为例)的更多相关文章
- 使用python解析Json字符串-获取Json字符串关键字
import json data = { "statusCode": 0, "data": { ", "height": &quo ...
- java遍历复杂json字符串获取想要的数据
https://blog.csdn.net/qq_34309663/article/details/80508125 java如何解析复杂的json数据关于json处理的包有好几个,比如jackson ...
- jquery,字符串转json对象,json对象转字符串
字符串转json对象 方法一:var json = eval('(' + str + ')'); 方法二:return JSON.parse(str); json对象转字符串 JSON.stringi ...
- java 字符串解析为json 使用org.json包的JSONObject+JSONArray
参考: https://blog.csdn.net/xingfei_work/article/details/76572550 java中四种json解析方式 JSONObject+JSONArray ...
- js进阶ajax读取json数据(ajax读取json和读取普通文本,和获取服务器返回数据(链接)都是一样的,在url处放上json文件的地址即可)
js进阶ajax读取json数据(ajax读取json和读取普通文本,和获取服务器返回数据(链接)都是一样的,在url处放上json文件的地址即可) 一.总结 ajax读取json和读取普通文本,和获 ...
- 富文本编辑器--获取JSON
获取 JSON 格式的内容 可以通过editor.txt.getJSON获取 JSON 格式的编辑器的内容,v3.0.14开始支持,示例如下 <div id="div1"&g ...
- 通过Jquery中Ajax获取json文件数据
1. JSON(JavaScript Object Notation): javaScript对象表示法: 是存储和交换文本信息的语法,比xml更小,更快,更易解析. 2. JSON基本书写格式 : ...
- HttpURLConnection从网上获取Json数据并解析详解
HttpURLConnection从网上获取Json数据并解析 1.HttpURLConnection请求数据的步骤 (1)构造一个URL接口地址: URL url = new URL("h ...
- Ajax获取Json多个集合并同时遍历
Ajax获取Json多个集合并同时遍历: 方法一.:将多个集合放入MAP集合. 后台:Servlet @Override protected void doPost(HttpServletReques ...
随机推荐
- python socket 编程之二:tcp三次握手
建立起一个TCP连接需要经过“三次握手”:第一次握手:客户端发送syn包(syn=j)到服务器,并进入SYN_SEND状态,等待服务器确认:第二次握手:服务器收到syn包,必须确认客户的SYN(ack ...
- nginx和apache的优缺点比较
简单的说apache httpd和nginx都是web服务器,但两者适应的场景不同,也就是两者专注于解决不同的问题.apache httpd:稳定.对动态请求处理强,但同时高并发时性能较弱,耗费资源多 ...
- oc语言--BLOCK和协议
一.BOLCK (一)简介 BLOCK是什么?苹果推荐的类型,效率高,在运行中保存代码.用来封装和保存代码,有点像函数,BLOCK可以在任何时候执行. BOLCK和函数的相似性:(1)可以保存代码(2 ...
- Android中动态更新TextView上的文字
示例代码: 1.新线程,定时更新文字 class testThread extends Thread{ public void run() { Message message = new Messag ...
- 源码编译安装 PHP5.5.0,解决curl_exec访问HTTPS返回502错误的问题(修改PATH路径)
最近碰到一个奇怪的问题, PHP使用 curl_exec 访问 HTTPS 网页时, 返回502错误, 访问HTTP网页时没有问题, 用 echo phpinfo() ; 查看, 支持op ...
- Qt中事件处理的方法(三种处理方法,四种覆盖event函数,notify函数,event过滤,事件处理器。然后继续传递给父窗口。可观察QWidget::event的源码,它是虚拟保护函数,可改写)
一.Qt中事件处理的方式 1.事件处理模式一 首先是事件源产生事件,最后是事件处理器对这些事件进行处理.然而也许大家会问, Qt中有这么多类的事件,我们怎么样比较简便的处理每个事件呢?设想,如果是 ...
- Erlang千万级用户游戏框架(Openpoker)源码文件分析清单
openpoker源码 erlang写的网游服务器源码,OpenPoker是一个大型多人扑克网游,内建支持了容错能力,负载平衡和无限制的规模大小.本文是openpoker源码文件功能的一个清单式说明: ...
- 中国版 Ubuntu Kylin 14.04 LTS 麒麟操作系统中文版发布下载 (Ubuntu天朝定制版)
中国版 Ubuntu Kylin 14.04 LTS 麒麟操作系统中文版发布下载 (Ubuntu天朝定制版) http://www.iplaysoft.com/ubuntukylin.html
- Valid Anagram 解答
Question Given two strings s and t, write a function to determine if t is an anagram of s. For examp ...
- LeeCode-Pow(x, n)
Implement pow(x, n). double myPow(double x, int n) { ) return 1.0; ) return 1.0/pow(x,-n); ); }