上次讲了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

Android 解析JSON的更多相关文章

  1. android解析json

    android2.3提供的json解析类 android的json解析部分都在包org.json下,主要有以下几个类: JSONObject:可以看作是一个json对象 JSONStringer:js ...

  2. 第十七章:android解析JSON

    一.解析JSON数据: 首先引入包import org.json.JSONObject;(android sdk 14以后应该自带了 ) Android端的程序解析JSON和JSON数组: packa ...

  3. Android解析Json速度最快的库:json-smart

    场景描写叙述: 本文仅验证了在安卓环境下使用Json的Key作为反序列化条件的解析速度.结论是解析速度最快的不是阿里的fastjson,也不是Google的Gson,而是json-smart. And ...

  4. 在android解析json

    1.采用一般方式解释json为对象 package com.heimazyh.testjson; import org.json.JSONException; import org.json.JSON ...

  5. Android解析Json数据之Gson解析

    Gson是谷歌官方提供的解析json数据的工具类.json数据的解析能够使用JSONObject和JSONArray配合使用解析数据,可是这样的原始的方法对于小数据的解析还是有作用的,可是陪到了复杂数 ...

  6. Android 解析JSON格式数据

    比起XML,JSON主要优势在于它的体积更小,在网络上传输的时候可以更省流量.但缺点在于,它的语义性较差,显示不如XML直观. JSON格式 :  { "name_A" : &qu ...

  7. Android解析json数据

    Json数据 [{"code":"110000","sheng":"11","di":"0 ...

  8. [转]Android解析json数据

    1.json格式 2.json解析 3.gson解析 4.fastjson解析 一.Json格式 json一种轻量级的数据交换格式.在网络上传输交换数据一般用xml, json. 两种结构: 1)对象 ...

  9. android解析json包(接口)

    package com.http.test; 02    03    04 import org.apache.http.HttpResponse; 05 import org.apache.http ...

随机推荐

  1. mac上常用的命令

    平时会经常遇到的问题做一个总结

  2. 【codeforces 801D】Volatile Kite

    [题目链接]:http://codeforces.com/contest/801/problem/D [题意] 给你一个凸多边形的n个点; 然后允许你将每个点移动到距离不超过D的范围内; 要求无论如何 ...

  3. 【codeforces 760D】Travel Card

    [题目链接]:http://codeforces.com/contest/760/problem/D [题意] 去旅行,有3种类型的乘车票; 第一种:只能旅行一次20元 第二种:按时间计算,90分钟内 ...

  4. Configuration must specify a spooling directory

    启动spooling源时报错: 原因:spooling配置文件有误 a1.sources.r1.type = spooldir a1.sources.r1.spooldir = /usr/local/ ...

  5. Servlet3.0中使用getPart进行文件上传

    这个先进些,简单些,但书上提供的例子不能使用,到处弄了弄才行. servlet代码: package cc.openhome; import java.io.InputStream; import j ...

  6. node.js 如何完美的从命令行接收参数所传递进来的值

    https://segmentfault.com/q/1010000000367285

  7. A*算法学习(转)

    A*启发式搜索算法详解 人工智能 1导言 1.1 算法 1.2 Dijkstra算法与最佳优先搜索 1.3 A*算法 2 启发式算法 2.1 A*对启发式函数的使用 2.2 速度还是精确度? 2.3  ...

  8. N天学习一个Linux命令之ln

    前言有时候同一个文件想创建多个别名,这个时候可以使用链接文件代替 用途对文件或者目录创建链接,默认创建的是硬链接 硬链接Linux底层文件系统由超级数据块,目录树对象,inode索引节点对象,文件对象 ...

  9. 如何重启apache2服务

    假设当前Linux用户的apahce安装目录为/usr/local/apache2,那么在命令行终端中使用以下命令启动,停止和重启apache.1. 启动apahce的命令:/usr/local/ap ...

  10. c++实现数据结构1.顺序表

    头文件seqlist.h #ifndef _SEQLIST_H_ #define _SEQLIST_H_ #include<iostream> using namespace std; t ...