上次讲了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":"武汉"}}
1 package com.example.weather; 2 3 import java.io.BufferedReader; 4 import java.io.InputStream; 5 import java.io.InputStreamReader; 6 import java.net.HttpURLConnection; 7 import java.net.URL; 8 import java.net.URLEncoder; 9 10 import org.json.JSONArray; 11 import org.json.JSONException; 12 import org.json.JSONObject; 13 14 import android.app.Activity; 15 import android.content.pm.ApplicationInfo; 16 import android.content.pm.PackageInfo; 17 import android.os.Bundle; 18 import android.os.Handler; 19 import android.os.Message; 20 import android.text.TextUtils; 21 import android.view.View; 22 import android.widget.EditText; 23 import android.widget.TextView; 24 import android.widget.Toast; 25 26 import com.example.weather.util.ReadStrean; 27 28 public class MainActivity extends Activity { 29 protected static final int SUCCESS = 0; 30 protected static final int ERROR =1; 31 protected static final int FAILL = 2; 32 private EditText et_city; 33 private TextView tv_one,tv_two,tv_three; 34 private String version; 35 private Handler handler=new Handler(){ 36 public void handleMessage(android.os.Message msg) { 37 switch (msg.what) { 38 case SUCCESS: 39 JSONArray array = (JSONArray)msg.obj; 40 try { 41 tv_one.setText(array.getString(0).toString()); 42 tv_two.setText(array.getString(1).toString()); 43 tv_three.setText(array.getString(2).toString()); 44 } catch (JSONException e) { 45 e.printStackTrace(); 46 } 47 break; 48 49 case ERROR: 50 Toast.makeText(MainActivity.this,"请输入正确的城市名称" , 0).show(); 51 break; 52 case FAILL: 53 Toast.makeText(MainActivity.this,"网络是否连接!" , 0).show(); 54 break; 55 } 56 }; 57 }; 58 59 @Override 60 protected void onCreate(Bundle savedInstanceState) { 61 super.onCreate(savedInstanceState); 62 setContentView(R.layout.activity_main); 63 initView(); 64 // initDate(); 65 } 66 67 // private void initDate() { 68 // try { 69 // PackageInfo info = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0); 70 // version= info.versionName; 71 // 72 // new Thread(){ 73 // public void run() { 74 // try { 75 // URL url=new URL("http://192.168.1.113:8080/version.json"); 76 // //打开网络连接 77 // HttpURLConnection conn= (HttpURLConnection) url.openConnection(); 78 // //设置连接方式"GET" 79 // conn.setRequestMethod("GET"); 80 // //设置http网络连接时间 81 // conn.setConnectTimeout(5000); 82 // //请求服务器得到一个返回码 83 // int code= conn.getResponseCode(); 84 // if(code == 200){ 85 // //getInputStream方法得到输入流其实就是从服务器端发回的数据 86 // InputStream is=conn.getInputStream(); 87 // StringBuilder builder=new StringBuilder(); 88 // int len; 89 // String line; 90 // BufferedReader read=new BufferedReader(new InputStreamReader(is)); 91 // while ((line = read.readLine())!=null) { 92 // builder.append(line); 93 // } 94 // is.close(); 95 // read.close(); 96 // String json = builder.toString(); 97 // System.out.println(json+"123456"); 98 // JSONObject object=new JSONObject(json); 99 // String appversion = object.getString("version"); 100 // if(version.equals(appversion)){ 101 // runOnUiThread(new Runnable() { 102 // public void run() { 103 // Toast.makeText(MainActivity.this, "暂无新版本", 0).show(); 104 // } 105 // }); 106 // }else { 107 // 108 // } 109 // } 110 // else { 111 // System.out.println("nononono"); 112 // } 113 // } catch (Exception e) { 114 // // TODO Auto-generated catch block 115 // e.printStackTrace(); 116 // } 117 // }; 118 // }.start(); 119 // } catch (Exception e) { 120 // // TODO Auto-generated catch block 121 // e.printStackTrace(); 122 // } 123 // } 124 125 private void initView() { 126 et_city=(EditText) findViewById(R.id.et_city); 127 tv_one=(TextView) findViewById(R.id.tv_one); 128 tv_two=(TextView) findViewById(R.id.tv_two); 129 tv_three=(TextView) findViewById(R.id.tv_three); 130 } 131 public void onclick (View v){ 132 final String city = et_city.getText().toString().trim(); 133 if(TextUtils.isEmpty(city)){ 134 Toast.makeText(this, "请输入城市名称", 0).show(); 135 return; 136 } 137 new Thread(){ 138 public void run() { 139 try { 140 String path="http://wthrcdn.etouch.cn/weather_mini?city="+URLEncoder.encode(city, "utf-8"); 141 URL url = new URL(path); 142 //打开网络连接 143 HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 144 //设置连接方式"GET" 145 conn.setRequestMethod("GET"); 146 //设置http网络连接时间 147 conn.setConnectTimeout(5000); 148 //请求服务器得到一个返回码 149 int code = conn.getResponseCode(); 150 if(code== 200){ 151 //getInputStream方法得到输入流其实就是从服务器端发回的数据 152 InputStream is= conn.getInputStream(); 153 String json = ReadStrean.readstreanUtil(is); 154 is.close(); 155 //创建一个JSONObject对象 156 JSONObject object= new JSONObject(json); 157 //取得json数据格式的第一个键,也是解析json数据的入口 158 String desc = object.getString("desc"); 159 if("OK".equals(desc)){ 160 //开始解析json 161 JSONObject data = object.getJSONObject("data"); 162 JSONArray array= data.getJSONArray("forecast"); 163 Message msg=new Message(); 164 msg.what=SUCCESS; 165 msg.obj=array; 166 handler.sendMessage(msg); 167 } 168 }else { 169 Message msg=new Message(); 170 msg.what=FAILL; 171 handler.sendMessage(msg); 172 } 173 174 } catch (Exception e) { 175 e.printStackTrace(); 176 Message msg=new Message(); 177 msg.what=ERROR; 178 handler.sendMessage(msg); 179 } 180 }; 181 182 }.start(); 183 184 } 185 }
自定义读取流的工具类:
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布局:
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" 6 tools:context="${relativePackage}.${activityClass}" > 7 8 <EditText 9 android:id="@+id/et_city" 10 android:layout_width="match_parent" 11 android:layout_height="wrap_content" 12 android:hint="请输入城市名称:" /> 13 14 <Button 15 android:id="@+id/btn_see" 16 android:onClick="onclick" 17 android:layout_width="match_parent" 18 android:layout_height="wrap_content" 19 android:text="查 看" /> 20 21 <TextView 22 android:id="@+id/tv_one" 23 android:layout_width="match_parent" 24 android:layout_height="0dip" 25 android:layout_weight="1" 26 android:text="今天" 27 android:textColor="#FF1493" /> 28 29 <TextView 30 android:layout_width="match_parent" 31 android:layout_height="1dp" 32 android:background="@android:color/darker_gray" /> 33 34 <TextView 35 android:id="@+id/tv_two" 36 android:layout_width="match_parent" 37 android:layout_height="0dip" 38 android:layout_weight="1" 39 android:text="明天" 40 android:textColor="#DC143C" /> 41 42 <TextView 43 android:layout_width="match_parent" 44 android:layout_height="1dp" 45 android:background="@android:color/darker_gray" /> 46 47 <TextView 48 android:id="@+id/tv_three" 49 android:layout_width="match_parent" 50 android:layout_height="0dip" 51 android:layout_weight="1" 52 android:text="后天" 53 android:textColor="#BC8F8F" /> 54 55 </LinearLayout>
最终解析显示图:
添加访问网络权限:<uses-permission android:name="android.permission.INTERNET"/>
源码下载地址:http://pan.baidu.com/s/1qXVGyZU