上次讲了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. 7-20 Windows消息队列 (25 分)(模拟水题)

    题意: 思路: 用优先队列直接模拟就OK了,另外优先队列存pair的时候比较的是first的值,实测!! 上代码: #include <iostream> #include <que ...

  2. 关于预测io调用的思考

    什么是预测io 预测io是linux2.6版本内核调用默认的调用程序,对应用程序进行跟踪,统计应用程序使用io情况,在读操作返回之前先停顿6ms时间(linux默认时间),如果这期间有读操作过来,可以 ...

  3. Sessions共享技术设计

    概述 分布式session是实现分布式部署的前提, 当前项目由于历史原因未实现分布式session, 但是由于在kubernets中部署多个pod时, 负载均衡的调用链太长, 导致会话不能保持, 所以 ...

  4. 腾讯云:ubuntu搭建 FTP 文件服务

    搭建 FTP 文件服务 安装并启动 FTP 服务 任务时间:5min ~ 10min 安装 VSFTPD 使用 apt-get 安装 vsftpd: sudo apt-get install vsft ...

  5. 前端开发神器之chrome 综述

    作为前端工程师,也许你对chrome开发工具不陌生,但也谈不上对各个模块有深入了解. 本文主要是为chrome开发工具使用这个系列做个开篇. 参考资料: 谷歌开发者: https://develope ...

  6. 关于在JSP页面中为什么一定要用${pageContext.request.contextPath}来获取项目路径,而不能用${request.contextPath}?

    这里的疑问在于pageContext和request都是JSP中的内置对象之一,为什么不直接用${request.contextPath}来获取项目路径? 出现这种疑问,其实是将JSP的内置对象和EL ...

  7. How to change java version in Linux

    How to change default Java version on Linux Posted on November 1, 2015 by Dan Nanni Leave a comment ...

  8. FineReport实线java报表填报录入的效果图

    Java报表-固定资产(增删改) Java报表-集团財务报表 Java报表-简单自由填报 Java报表-客户跟踪数据回填 Java报表-客户关系复杂填报 Java报表-批量导入 Java报表-批量删除 ...

  9. web 文件上传组件 Plupload

    Plupload官网:点击打开链接   建议下载最新版本号,低版本号会出现浏览器兼容问题. 近期公司有个项目须要在web端使用多文件上传功能.刚開始准备使用HTML5来做.但是IE9下面是都不支持的, ...

  10. 被AppStore拒绝理由(一)

    July 8, 2015 at 7:06 AM 发件人 Apple 17.1 - Apps cannot transmit data about a user without obtaining th ...