日本搞逼视频_黄色一级片免费在线观看_色99久久_性明星video另类hd_欧美77_综合在线视频

國內(nèi)最全IT社區(qū)平臺 聯(lián)系我們 | 收藏本站
阿里云優(yōu)惠2
您當前位置:首頁 > php開源 > 綜合技術(shù) > Android之JSON格式數(shù)據(jù)解析

Android之JSON格式數(shù)據(jù)解析

來源:程序員人生   發(fā)布時間:2015-01-07 08:13:08 閱讀次數(shù):4813次
JSON:JavaScript 對象表示法(JavaScript Object Notation)。獨立于語言和平臺,比 XML 更小、更快,更容易解析。如今JSON數(shù)據(jù)已成了互聯(lián)網(wǎng)中大多數(shù)數(shù)據(jù)的傳遞方式,所以必須要熟練掌握。

Android平臺自帶了JSON解析的相干API,可以將文件、輸入流中的數(shù)據(jù)轉(zhuǎn)化為JSON對象,然后從對象中獲得JSON保存的數(shù)據(jù)內(nèi)容。


Android的JSON解析部份都在包org.json下,主要有以下幾個類: 
JSONObject:可以看做是1個json對象,這是系統(tǒng)中有關(guān)JSON定義的基本單元,其包括1對兒(Key/Value)數(shù)值。它對外部(External:利用toString()方法輸出的數(shù)值)調(diào)用的響應體現(xiàn)為1個標準的字符串(例如:{"JSON": "Hello, World"},最外被大括號包裹,其中的Key和Value被冒號":"分隔)。其對內(nèi)部(Internal)行動的操作格式稍微,例如:初始化1個JSONObject實例,援用內(nèi)部的put()方法添加數(shù)值:new JSONObject().put("JSON", "Hello, World!"),在Key和Value之間是以逗號","分隔。Value的類型包括:Boolean、JSONArray、JSONObject、Number、String或默許值JSONObject.NULL object。

JSONStringer:json文本構(gòu)建類 ,根據(jù)官方的解釋,這個類可以幫助快速和便捷的創(chuàng)建JSON text。其最大的優(yōu)點在于可以減少由于 格式的毛病致使程序異常,援用這個類可以自動嚴格依照JSON語法規(guī)則(syntax rules)創(chuàng)建JSON text。每一個JSONStringer實體只能對應創(chuàng)建1個JSON text。。其最大的優(yōu)點在于可以減少由于格式的毛病致使程序異常,援用這個類可以自動嚴格依照JSON語法規(guī)則(syntax rules)創(chuàng)建JSON text。每一個JSONStringer實體只能對應創(chuàng)建1個JSON text。

JSONArray:它代表1組有序的數(shù)值。將其轉(zhuǎn)換為String輸出(toString)所表現(xiàn)的情勢是用方括號包裹,數(shù)值以逗號”,”分隔(例如:[value1,value2,value3],大家可以親身利用簡短的代碼更加直觀的了解其格式)。這個類的內(nèi)部一樣具有查詢行動,get()和opt()兩種方法都可以通過index索引返回指定的數(shù)值,put()方法用來添加或替換數(shù)值。一樣這個類的value類型可以包括:Boolean、JSONArray、JSONObject、Number、String或默許值JSONObject.NULL object。

JSONTokener:json解析類
JSONException:json中用到的異常

下面以聚合數(shù)據(jù)空氣質(zhì)量城市空氣PM2.5指數(shù)數(shù)據(jù)接口為例來演示JSON格式數(shù)據(jù)的解析。
聚合數(shù)據(jù)空氣質(zhì)量城市空氣PM2.5指數(shù)數(shù)據(jù)接口API文檔參見:http://www.juhe.cn/docs/api/id/33/aid/79
JSON返回示例:
{ /*JSONObject*/
    "resultcode": "200",
    "reason": "SUCCESSED!",
    "result": [ /*JSONArray*/
        { /*JSONObject*/
            "city": "蘇州",  /*城市*/
            "PM2.5": "73",  /*PM2.5指數(shù)*/
            "AQI": "98",    /*空氣質(zhì)量指數(shù)*/
            "quality": "良", /*空氣質(zhì)量*/
            "PM10": "50",/*PM10*/
            "CO": "0.79",  /*1氧化碳*/
            "NO2": "65",  /*2氧化氮*/
            "O3": "28",    /*臭氧*/
            "SO2": "41",  /*2氧化硫*/
            "time": "2014⑴2⑵6 11:48:40"/*更新時間*/  
        }
    ],
    "error_code": 0
}

實例:JSONDemo
運行效果:

代碼清單:
布局文件:activity_main.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=".MainActivity" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:text="城市:" android:textSize="23sp" /> <EditText android:id="@+id/city" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="3" android:inputType="text" />" </LinearLayout> <Button android:id="@+id/query" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="查詢" android:textSize="23sp" /> <TextView android:id="@+id/result" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>

Java源代碼文件:MainActivity.java
package com.rainsong.jsondemo; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { EditText et_city; Button btn_query; TextView tv_result; QueryTask task; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_city = (EditText)findViewById(R.id.city); tv_result = (TextView)findViewById(R.id.result); btn_query = (Button)findViewById(R.id.query); btn_query.setOnClickListener(new OnClickListener() { public void onClick(View view) { String city = et_city.getText().toString(); if (city.length() < 1) { Toast.makeText(MainActivity.this, "請輸入城市名", Toast.LENGTH_LONG).show(); return; } task = new QueryTask(MainActivity.this, tv_result); task.execute(city); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }

Java源代碼文件:QueryTask.java
package com.rainsong.jsondemo; import java.io.IOException; import java.net.URLEncoder; import java.util.ArrayList; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.os.AsyncTask; import android.widget.TextView; import android.widget.Toast; public class QueryTask extends AsyncTask<String, Void, String> { Context context; TextView tv_result; private static final String JUHE_URL_ENVIRONMENT_AIR_PM = "http://web.juhe.cn:8080/environment/air/pm"; private static final String JUHE_APPKEY = "你申請的APPKEY值"; public QueryTask(Context context, TextView tv_result) { // TODO Auto-generated constructor stub super(); this.context = context; this.tv_result = tv_result; } @Override protected String doInBackground(String... params) { String city = params[0]; ArrayList<NameValuePair> headerList = new ArrayList<NameValuePair>(); headerList.add(new BasicNameValuePair("Content-Type", "text/html; charset=utf⑻")); String targetUrl = JUHE_URL_ENVIRONMENT_AIR_PM; ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>(); paramList.add(new BasicNameValuePair("key", JUHE_APPKEY)); paramList.add(new BasicNameValuePair("dtype", "json")); paramList.add(new BasicNameValuePair("city", city)); for (int i = 0; i < paramList.size(); i++) { NameValuePair nowPair = paramList.get(i); String value = nowPair.getValue(); try { value = URLEncoder.encode(value, "UTF⑻"); } catch (Exception e) { } if (i == 0) { targetUrl += ("?" + nowPair.getName() + "=" + value); } else { targetUrl += ("&" + nowPair.getName() + "=" + value); } } HttpGet httpRequest = new HttpGet(targetUrl); try { for (int i = 0; i < headerList.size(); i++) { httpRequest.addHeader(headerList.get(i).getName(), headerList.get(i).getValue()); } HttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(httpRequest); if (httpResponse.getStatusLine().getStatusCode() == 200) { String strResult = EntityUtils.toString(httpResponse.getEntity()); return strResult; } else { return null; } } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String result) { if (result != null) { try { JSONObject jsonObject = new JSONObject(result); int resultCode = jsonObject.getInt("resultcode"); if (resultCode == 200) { JSONArray resultJsonArray = jsonObject.getJSONArray("result"); JSONObject resultJsonObject = resultJsonArray.getJSONObject(0); String output = context.getString(R.string.city) + ": " + resultJsonObject.getString("city") + " " + context.getString(R.string.PM25) + ": " + resultJsonObject.getString("PM2.5") + " " + context.getString(R.string.AQI) + ": " + resultJsonObject.getString("AQI") + " " + context.getString(R.string.quality) + ": " + resultJsonObject.getString("quality") + " " + context.getString(R.string.PM10) + ": " + resultJsonObject.getString("PM10") + " " + context.getString(R.string.CO) + ": " + resultJsonObject.getString("CO") + " " + context.getString(R.string.NO2) + ": " + resultJsonObject.getString("NO2") + " " + context.getString(R.string.O3) + ": " + resultJsonObject.getString("O3") + " " + context.getString(R.string.SO2) + ": " + resultJsonObject.getString("SO2") + " " + context.getString(R.string.time) + ": " + resultJsonObject.getString("time") + " "; tv_result.setText(output); } else if (resultCode == 202) { String reason = jsonObject.getString("reason"); tv_result.setText(reason); } else { Toast.makeText(context, "查詢失敗", Toast.LENGTH_LONG).show(); tv_result.setText(""); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { Toast.makeText(context, "查詢失敗", Toast.LENGTH_LONG).show(); tv_result.setText(""); } } }

字符串資源:string.xml

<?xml version="1.0" encoding="utf⑻"?> <resources> <string name="app_name">JSONDemo</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="city">城市</string> <string name="PM25">PM2.5指數(shù)</string> <string name="AQI">空氣質(zhì)量指數(shù)</string> <string name="quality">空氣質(zhì)量</string> <string name="PM10">PM10</string> <string name="CO">1氧化碳</string> <string name="NO2">2氧化氮</string> <string name="O3">臭氧</string> <string name="SO2">2氧化硫</string> <string name="time">更新時間</string> </resources>


API知識點
public class 
JSONObject
extends Object

org.json.JSONObject

Class Overview
A modifiable set of name/value mappings. Names are unique, non-null strings. Values may be any mix of JSONObjects, JSONArrays, Strings, Booleans, Integers, Longs, Doubles or NULL. Values may not be null, NaNs, infinities, or of any type not listed here. 

JSONObject(String json) 
Creates a new JSONObject with name/value mappings from the JSON string.
 
Object  get(String name) 
Returns the value mapped by name. 

int  getInt(String name) 
Returns the value mapped by name if it exists and is an int or can be coerced to an int. 

String  getString(String name) 
Returns the value mapped by name if it exists, coercing it if necessary. 

JSONArray  getJSONArray(String name) 
Returns the value mapped by name if it exists and is a JSONArray. 

public class 
JSONArray
extends Object

org.json.JSONArray

Class Overview
A dense indexed sequence of values. Values may be any mix of JSONObjects, other JSONArrays, Strings, Booleans, Integers, Longs, Doubles, null or NULL. Values may not be NaNs, infinities, or of any type not listed here. 

JSONObject  getJSONObject(int index) 

Returns the value at index if it exists and is a JSONObject. 


生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學習有所幫助,可以手機掃描二維碼進行捐贈
程序員人生
------分隔線----------------------------
分享到:
------分隔線----------------------------
關(guān)閉
程序員人生
主站蜘蛛池模板: 爱久久久| 91精品国产综合久久福利不卡 | 国产视 | 成人在线网| 婷婷综合五月 | 欧美电影一区 | 91久久国产综合久久91精品网站 | 99久久国| 国产欧美精品在线 | av中文字幕一区 | www久久精品 | 欧美一区二区网站 | 91精品视频在线 | 国产二区在线播放 | 18视频网站在线观看 | 国产精品视频免费在线观看 | 国产伦精品一区二区三区免费 | 中文字幕日本视频 | 国产福利影院 | 欧美日韩在线视频观看 | 爽爽影院在线看 | 黄色小视频在线播放 | 亚洲久久久 | 黑人精品 | 亚洲成色999久久网站 | 美女久久| 男女上床网站 | 久久久青草婷婷精品综合日韩 | 日韩欧美亚洲一区二区 | 国产视频一二区 | 欧美午夜一区二区三区 | 国产精品久久久av久久久 | 国产区网址| 爱综合 | 麻豆视频在线免费观看 | 国产黄色免费网站 | 精品福利一区二区三区 | 国产精品久久久久久久免费大片 | 91av电影在线观看 | 欧美一级黄色片 | 欧美伊人 |