上次讲了XML格式数据的解析方式,这次要说的是如何解析JSON数据格式,相对与XML,JSON解析数据的方式在于它的体积更小,在网络上传输可以更省流量。

  这次在网上找到一个中国天气json数据的API接口,这就更便于我们直接去解析别人弄好的数据拿来使用,下面这是从网上下载json文件,当然也可以自己简单的编辑:

{"desc":"OK","status":1000,"data":{"wendu":"25","ganmao":"相对于今天将会出现大幅度降温,风力较大,易发生感冒,请注意适当增加衣服。","forecast":[{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 26℃","type":"多云","low":"低温 17℃","date":"2日星期二"},{"fengxiang":"无持续风向","fengli":"5-6级","high":"高温 22℃","type":"大雨","low":"低温 17℃","date":"3日星期三"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 25℃","type":"晴","low":"低温 15℃","date":"4日星期四"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 27℃","type":"晴","low":"低温 16℃","date":"5日星期五"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 23℃","type":"阴","low":"低温 16℃","date":"6日星期六"}],"yesterday":{"fl":"微风","fx":"东风","high":"高温 23℃","type":"中雨","low":"低温 15℃","date":"1日星期一"},"aqi":"79","city":"武汉"}}

  

 package com.example.weather;

 import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder; import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject; import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast; import com.example.weather.util.ReadStrean; public class MainActivity extends Activity {
protected static final int SUCCESS = 0;
protected static final int ERROR =1;
protected static final int FAILL = 2;
private EditText et_city;
private TextView tv_one,tv_two,tv_three;
private String version;
private Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case SUCCESS:
JSONArray array = (JSONArray)msg.obj;
try {
tv_one.setText(array.getString(0).toString());
tv_two.setText(array.getString(1).toString());
tv_three.setText(array.getString(2).toString());
} catch (JSONException e) {
e.printStackTrace();
}
break; case ERROR:
Toast.makeText(MainActivity.this,"请输入正确的城市名称" , 0).show();
break;
case FAILL:
Toast.makeText(MainActivity.this,"网络是否连接!" , 0).show();
break;
}
};
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
// initDate();
} // private void initDate() {
// try {
// PackageInfo info = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0);
// version= info.versionName;
//
// new Thread(){
// public void run() {
// try {
// URL url=new URL("http://192.168.1.113:8080/version.json");
// //打开网络连接
// HttpURLConnection conn= (HttpURLConnection) url.openConnection();
// //设置连接方式"GET"
// conn.setRequestMethod("GET");
// //设置http网络连接时间
// conn.setConnectTimeout(5000);
// //请求服务器得到一个返回码
// int code= conn.getResponseCode();
// if(code == 200){
// //getInputStream方法得到输入流其实就是从服务器端发回的数据
// InputStream is=conn.getInputStream();
// StringBuilder builder=new StringBuilder();
// int len;
// String line;
// BufferedReader read=new BufferedReader(new InputStreamReader(is));
// while ((line = read.readLine())!=null) {
// builder.append(line);
// }
// is.close();
// read.close();
// String json = builder.toString();
// System.out.println(json+"123456");
// JSONObject object=new JSONObject(json);
// String appversion = object.getString("version");
// if(version.equals(appversion)){
// runOnUiThread(new Runnable() {
// public void run() {
// Toast.makeText(MainActivity.this, "暂无新版本", 0).show();
// }
// });
// }else {
//
// }
// }
// else {
// System.out.println("nononono");
// }
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// };
// }.start();
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// } private void initView() {
et_city=(EditText) findViewById(R.id.et_city);
tv_one=(TextView) findViewById(R.id.tv_one);
tv_two=(TextView) findViewById(R.id.tv_two);
tv_three=(TextView) findViewById(R.id.tv_three);
}
public void onclick (View v){
final String city = et_city.getText().toString().trim();
if(TextUtils.isEmpty(city)){
Toast.makeText(this, "请输入城市名称", 0).show();
return;
}
new Thread(){
public void run() {
try {
String path="http://wthrcdn.etouch.cn/weather_mini?city="+URLEncoder.encode(city, "utf-8");
URL url = new URL(path);
//打开网络连接
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置连接方式"GET"
conn.setRequestMethod("GET");
//设置http网络连接时间
conn.setConnectTimeout(5000);
//请求服务器得到一个返回码
int code = conn.getResponseCode();
if(code== 200){
//getInputStream方法得到输入流其实就是从服务器端发回的数据
InputStream is= conn.getInputStream();
String json = ReadStrean.readstreanUtil(is);
is.close();
//创建一个JSONObject对象
JSONObject object= new JSONObject(json);
//取得json数据格式的第一个键,也是解析json数据的入口
String desc = object.getString("desc");
if("OK".equals(desc)){
//开始解析json
JSONObject data = object.getJSONObject("data");
JSONArray array= data.getJSONArray("forecast");
Message msg=new Message();
msg.what=SUCCESS;
msg.obj=array;
handler.sendMessage(msg);
}
}else {
Message msg=new Message();
msg.what=FAILL;
handler.sendMessage(msg);
} } catch (Exception e) {
e.printStackTrace();
Message msg=new Message();
msg.what=ERROR;
handler.sendMessage(msg);
}
}; }.start(); }
}

自定义读取流的工具类:

package com.example.weather.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream; public class ReadStrean {
public static String readstreanUtil(InputStream is) throws IOException{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len;
byte [] arr=new byte[1024];
while((len=is.read(arr))!=-1){
bos.write(arr, 0, len);
}
is.close();
bos.close();
return bos.toString("utf-8"); }
}

xml布局:

 <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="${relativePackage}.${activityClass}" > <EditText
android:id="@+id/et_city"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入城市名称:" /> <Button
android:id="@+id/btn_see"
android:onClick="onclick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="查 看" /> <TextView
android:id="@+id/tv_one"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:text="今天"
android:textColor="#FF1493" /> <TextView
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@android:color/darker_gray" /> <TextView
android:id="@+id/tv_two"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:text="明天"
android:textColor="#DC143C" /> <TextView
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@android:color/darker_gray" /> <TextView
android:id="@+id/tv_three"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:text="后天"
android:textColor="#BC8F8F" /> </LinearLayout>

最终解析显示图:

添加访问网络权限:<uses-permission android:name="android.permission.INTERNET"/>

源码下载地址:http://pan.baidu.com/s/1qXVGyZU

最新文章

  1. ACM: FZU 2105 Digits Count - 位运算的线段树【黑科技福利】
  2. 转载:Tomcat的JVM设置和连接数设置
  3. Amazon Resource Names (ARNs)
  4. Python 类变量和成员变量
  5. C++排列对称串
  6. C++:String类
  7. sqlserver 2008express版本启用混合登陆和sa
  8. MyEclipse_6.0.1GA_E3.3.1集成版下载地址
  9. OSI模型和TCP/IP协议族(一)
  10. go 终端读写、文件读写
  11. 关于pythoh面向过程开发人员三步转面向对象的补充,再加一步,四步走战略。转面向对象也可以有固定公式。
  12. linux下GCC编译文件
  13. Android 框架式编程 —— 起篇
  14. net4log 日志管理
  15. C# 方法中的this参数
  16. 元素位置pageX,pageY,clientX,clientY,scrollX,scrollY,screenX,screenY,offsetX,offsetY
  17. std::string 的方法c_str() 和 data() 有什么区别
  18. PCP项目立项
  19. session的取代者:Json Web Tokens----在客户端存储登陆状态
  20. net user 修改密码的坑

热门文章

  1. Spring整合Junit框架进行单元测试Demo
  2. 曾经遇过的sql问题
  3. Ubuntu | Flask + Gunicorn + Nginx 部署服务器环境
  4. Huawei-R&amp;S-网络工程师实验笔记20190527-华为设备密码重置、设置web管理
  5. linux学习7-数据流重定向
  6. Dajngo——10 请求与响应 文件上传 GET和POST请求 类视图
  7. STM32的独立看门狗
  8. POJ 3748:位操作
  9. Codeforces Round #Pi (Div. 2) —— C-Geometric Progression
  10. 深入理解Java和MySQL乱码问题