JSON格式数据分析

JSON:JavaScript 对象表示法(JavaScript Object Notation)。独立于语言和平台,比 XML 更小、更快,更易解析。如今JSON数据已经成为了互联网中大多数数据的传递方式,所以必须要熟练掌握。

Android平台自带了JSON解析的相关API,可以将文件、输入流中的数据转化为JSON对象,然后从对象中获取JSON保存的数据内容。


Android的JSON解析部分都在包org.json下,主要有以下几个类: 
JSONObject:可以看作是一个json对象,这是系统中有关JSON定义的基本单元,其包含一对儿(Key/Value)数值。它对外部(External:应用toString()方法输出的数值)调用的响应体现为一个标准的字符串(例如:{"JSON": "Hello, World"},最外被大括号包裹,其中的Key和Value被冒号":"分隔)。其对于内部(Internal)行为的操作格式略微,例如:初始化一个JSONObject实例,引用内部的put()方法添加数值:new JSONObject().put("JSON", "Hello, World!"),在Key和Value之间是以逗号","分隔。Value的类型包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object。

JSONStringer:json文本构建类 ,根据官方的解释,这个类可以帮助快速和便捷的创建JSON text。其最大的优点在于可以减少由于 格式的错误导致程序异常,引用这个类可以自动严格按照JSON语法规则(syntax rules)创建JSON text。每个JSONStringer实体只能对应创建一个JSON text。。其最大的优点在于可以减少由于格式的错误导致程序异常,引用这个类可以自动严格按照JSON语法规则(syntax rules)创建JSON text。每个JSONStringer实体只能对应创建一个JSON text。

JSONArray:它代表一组有序的数值。将其转换为String输出(toString)所表现的形式是用方括号包裹,数值以逗号”,”分隔(例如:[value1,value2,value3],大家可以亲自利用简短的代码更加直观的了解其格式)。这个类的内部同样具有查询行为,get()和opt()两种方法都可以通过index索引返回指定的数值,put()方法用来添加或者替换数值。同样这个类的value类型可以包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object。

JSONTokener:json解析类
JSONException:json中用到的异常

下面以聚合数据空气质量城市空气PM2.5指数数据接口为例来演示JSON格式数据的解析。
聚合数据空气质量城市空气PM2.5指数数据接口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指数*/
            "AQI": "98",    /*空气质量指数*/
            "quality": "良", /*空气质量*/
            "PM10": "50",/*PM10*/
            "CO": "0.79",  /*一氧化碳*/
            "NO2": "65",  /*二氧化氮*/
            "O3": "28",    /*臭氧*/
            "SO2": "41",  /*二氧化硫*/
            "time": "2014-12-26 11:48:40"/*更新时间*/  
        }
    ],
    "error_code": 0
}

实例:JSONDemo
运行效果:

代码清单:
布局文件:activity_main.xml
[html]  view plain  copy
  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=".MainActivity" >  
  7.   
  8.     <LinearLayout   
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="wrap_content"   
  11.         android:orientation="horizontal" >  
  12.   
  13.         <TextView  
  14.             android:layout_width="wrap_content"  
  15.             android:layout_height="wrap_content"  
  16.             android:layout_weight="1"  
  17.             android:gravity="center"  
  18.             android:text="城市:"  
  19.             android:textSize="23sp" />  
  20.   
  21.         <EditText   
  22.             android:id="@+id/city"  
  23.             android:layout_width="wrap_content"  
  24.             android:layout_height="wrap_content"  
  25.             android:layout_weight="3"  
  26.             android:inputType="text" />"  
  27.     </LinearLayout>  
  28.   
  29.     <Button  
  30.         android:id="@+id/query"  
  31.         android:layout_width="match_parent"  
  32.         android:layout_height="wrap_content"   
  33.         android:text="查询"   
  34.         android:textSize="23sp" />  
  35.       
  36.     <TextView  
  37.         android:id="@+id/result"  
  38.         android:layout_width="match_parent"  
  39.         android:layout_height="match_parent" />  
  40. </LinearLayout>  

Java源代码文件:MainActivity.java
[java]  view plain  copy
  1. package com.rainsong.jsondemo;  
  2.   
  3. import android.os.Bundle;  
  4. import android.app.Activity;  
  5. import android.view.Menu;  
  6. import android.view.View;  
  7. import android.view.View.OnClickListener;  
  8. import android.widget.Button;  
  9. import android.widget.EditText;  
  10. import android.widget.TextView;  
  11. import android.widget.Toast;  
  12.   
  13. public class MainActivity extends Activity {  
  14.     EditText et_city;  
  15.     Button btn_query;  
  16.     TextView tv_result;  
  17.     QueryTask task;  
  18.   
  19.     @Override  
  20.     protected void onCreate(Bundle savedInstanceState) {  
  21.         super.onCreate(savedInstanceState);  
  22.         setContentView(R.layout.activity_main);  
  23.   
  24.         et_city = (EditText)findViewById(R.id.city);  
  25.         tv_result = (TextView)findViewById(R.id.result);  
  26.         btn_query = (Button)findViewById(R.id.query);  
  27.   
  28.         btn_query.setOnClickListener(new OnClickListener() {  
  29.             public void onClick(View view) {  
  30.                 String city = et_city.getText().toString();  
  31.                 if (city.length() < 1) {  
  32.                     Toast.makeText(MainActivity.this"请输入城市名",  
  33.                             Toast.LENGTH_LONG).show();  
  34.                     return;  
  35.                 }  
  36.                 task = new QueryTask(MainActivity.this, tv_result);  
  37.                 task.execute(city);  
  38.             }  
  39.         });  
  40.     }  
  41.   
  42.     @Override  
  43.     public boolean onCreateOptionsMenu(Menu menu) {  
  44.         // Inflate the menu; this adds items to the action bar if it is present.  
  45.         getMenuInflater().inflate(R.menu.main, menu);  
  46.         return true;  
  47.     }  
  48.   
  49. }  

Java源代码文件:QueryTask.java
[java]  view plain  copy
  1. package com.rainsong.jsondemo;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.URLEncoder;  
  5. import java.util.ArrayList;  
  6.   
  7. import org.apache.http.HttpResponse;  
  8. import org.apache.http.NameValuePair;  
  9. import org.apache.http.client.HttpClient;  
  10. import org.apache.http.client.methods.HttpGet;  
  11. import org.apache.http.impl.client.DefaultHttpClient;  
  12. import org.apache.http.message.BasicNameValuePair;  
  13. import org.apache.http.util.EntityUtils;  
  14. import org.json.JSONArray;  
  15. import org.json.JSONException;  
  16. import org.json.JSONObject;  
  17.   
  18. import android.content.Context;  
  19. import android.os.AsyncTask;  
  20. import android.widget.TextView;  
  21. import android.widget.Toast;  
  22.   
  23. public class QueryTask extends AsyncTask<String, Void, String> {  
  24.     Context context;  
  25.     TextView tv_result;  
  26.   
  27.     private static final String JUHE_URL_ENVIRONMENT_AIR_PM =   
  28.                                     "http://web.juhe.cn:8080/environment/air/pm";  
  29.     private static final String JUHE_APPKEY = "你申请的APPKEY值";  
  30.   
  31.     public QueryTask(Context context, TextView tv_result) {  
  32.         // TODO Auto-generated constructor stub  
  33.         super();  
  34.         this.context = context;  
  35.         this.tv_result = tv_result;   
  36.     }  
  37.   
  38.     @Override  
  39.     protected String doInBackground(String... params) {  
  40.         String city = params[0];  
  41.   
  42.         ArrayList<NameValuePair> headerList = new ArrayList<NameValuePair>();  
  43.         headerList.add(new BasicNameValuePair("Content-Type""text/html; charset=utf-8"));  
  44.   
  45.         String targetUrl = JUHE_URL_ENVIRONMENT_AIR_PM;  
  46.   
  47.         ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();  
  48.         paramList.add(new BasicNameValuePair("key", JUHE_APPKEY));  
  49.         paramList.add(new BasicNameValuePair("dtype""json"));  
  50.         paramList.add(new BasicNameValuePair("city", city));  
  51.   
  52.         for (int i = 0; i < paramList.size(); i++) {  
  53.             NameValuePair nowPair = paramList.get(i);  
  54.             String value = nowPair.getValue();  
  55.             try {  
  56.                 value = URLEncoder.encode(value, "UTF-8");  
  57.             } catch (Exception e) {  
  58.             }  
  59.             if (i == 0) {  
  60.                 targetUrl += ("?" + nowPair.getName() + "=" + value);  
  61.             } else {  
  62.                 targetUrl += ("&" + nowPair.getName() + "=" + value);  
  63.             }  
  64.         }  
  65.   
  66.         HttpGet httpRequest = new HttpGet(targetUrl);  
  67.         try {  
  68.             for (int i = 0; i < headerList.size(); i++) {  
  69.                 httpRequest.addHeader(headerList.get(i).getName(),  
  70.                                         headerList.get(i).getValue());  
  71.             }  
  72.   
  73.             HttpClient httpClient = new DefaultHttpClient();  
  74.   
  75.             HttpResponse httpResponse = httpClient.execute(httpRequest);  
  76.             if (httpResponse.getStatusLine().getStatusCode() == 200) {  
  77.                 String strResult = EntityUtils.toString(httpResponse.getEntity());  
  78.                 return strResult;  
  79.             } else {  
  80.                 return null;  
  81.             }  
  82.         } catch (IOException e) {  
  83.             e.printStackTrace();  
  84.         }  
  85.         return null;  
  86.     }  
  87.   
  88.     @Override    
  89.     protected void onPostExecute(String result) {  
  90.         if (result != null) {  
  91.             try {  
  92.                 JSONObject jsonObject = new JSONObject(result);  
  93.                 int resultCode = jsonObject.getInt("resultcode");  
  94.                 if (resultCode == 200) {  
  95.                     JSONArray resultJsonArray = jsonObject.getJSONArray("result");  
  96.                     JSONObject resultJsonObject = resultJsonArray.getJSONObject(0);  
  97.                     String output = context.getString(R.string.city) + ": " + resultJsonObject.getString("city") + "\n"  
  98.                             + context.getString(R.string.PM25) + ": " + resultJsonObject.getString("PM2.5") + "\n"  
  99.                             + context.getString(R.string.AQI) + ": " + resultJsonObject.getString("AQI") + "\n"  
  100.                             + context.getString(R.string.quality) + ": " + resultJsonObject.getString("quality") + "\n"  
  101.                             + context.getString(R.string.PM10) + ": " + resultJsonObject.getString("PM10") + "\n"  
  102.                             + context.getString(R.string.CO) + ": " + resultJsonObject.getString("CO") + "\n"  
  103.                             + context.getString(R.string.NO2) + ": " + resultJsonObject.getString("NO2") + "\n"  
  104.                             + context.getString(R.string.O3) + ": " + resultJsonObject.getString("O3") + "\n"  
  105.                             + context.getString(R.string.SO2) + ": " + resultJsonObject.getString("SO2") + "\n"  
  106.                             + context.getString(R.string.time) + ": " + resultJsonObject.getString("time") + "\n";  
  107.                     tv_result.setText(output);  
  108.                 } else if (resultCode == 202) {  
  109.                     String reason = jsonObject.getString("reason");  
  110.                     tv_result.setText(reason);  
  111.                 } else {  
  112.                     Toast.makeText(context, "查询失败",  
  113.                             Toast.LENGTH_LONG).show();  
  114.                     tv_result.setText("");  
  115.                 }  
  116.             } catch (JSONException e) {  
  117.                 // TODO Auto-generated catch block  
  118.                 e.printStackTrace();  
  119.             }  
  120.         } else {  
  121.             Toast.makeText(context, "查询失败",  
  122.                                     Toast.LENGTH_LONG).show();  
  123.             tv_result.setText("");  
  124.         }  
  125.     }    
  126.     
  127. }  

字符串资源:string.xml

[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.   
  4.     <string name="app_name">JSONDemo</string>  
  5.     <string name="action_settings">Settings</string>  
  6.     <string name="hello_world">Hello world!</string>  
  7.   
  8.     <string name="city">城市</string>  
  9.     <string name="PM25">PM2.5指数</string>  
  10.     <string name="AQI">空气质量指数</string>  
  11.     <string name="quality">空气质量</string>  
  12.     <string name="PM10">PM10</string>  
  13.     <string name="CO">一氧化碳</string>  
  14.     <string name="NO2">二氧化氮</string>  
  15.     <string name="O3">臭氧</string>  
  16.     <string name="SO2">二氧化硫</string>  
  17.     <string name="time">更新时间</string>  
  18.       
  19. </resources>  
JSON:JavaScript 对象表示法(JavaScript Object Notation)。独立于语言和平台,比 XML 更小、更快,更易解析。如今JSON数据已经成为了互联网中大多数数据的传递方式,所以必须要熟练掌握。

Android平台自带了JSON解析的相关API,可以将文件、输入流中的数据转化为JSON对象,然后从对象中获取JSON保存的数据内容。


Android的JSON解析部分都在包org.json下,主要有以下几个类: 
JSONObject:可以看作是一个json对象,这是系统中有关JSON定义的基本单元,其包含一对儿(Key/Value)数值。它对外部(External:应用toString()方法输出的数值)调用的响应体现为一个标准的字符串(例如:{"JSON": "Hello, World"},最外被大括号包裹,其中的Key和Value被冒号":"分隔)。其对于内部(Internal)行为的操作格式略微,例如:初始化一个JSONObject实例,引用内部的put()方法添加数值:new JSONObject().put("JSON", "Hello, World!"),在Key和Value之间是以逗号","分隔。Value的类型包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object。

JSONStringer:json文本构建类 ,根据官方的解释,这个类可以帮助快速和便捷的创建JSON text。其最大的优点在于可以减少由于 格式的错误导致程序异常,引用这个类可以自动严格按照JSON语法规则(syntax rules)创建JSON text。每个JSONStringer实体只能对应创建一个JSON text。。其最大的优点在于可以减少由于格式的错误导致程序异常,引用这个类可以自动严格按照JSON语法规则(syntax rules)创建JSON text。每个JSONStringer实体只能对应创建一个JSON text。

JSONArray:它代表一组有序的数值。将其转换为String输出(toString)所表现的形式是用方括号包裹,数值以逗号”,”分隔(例如:[value1,value2,value3],大家可以亲自利用简短的代码更加直观的了解其格式)。这个类的内部同样具有查询行为,get()和opt()两种方法都可以通过index索引返回指定的数值,put()方法用来添加或者替换数值。同样这个类的value类型可以包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object。

JSONTokener:json解析类
JSONException:json中用到的异常

下面以聚合数据空气质量城市空气PM2.5指数数据接口为例来演示JSON格式数据的解析。
聚合数据空气质量城市空气PM2.5指数数据接口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指数*/
            "AQI": "98",    /*空气质量指数*/
            "quality": "良", /*空气质量*/
            "PM10": "50",/*PM10*/
            "CO": "0.79",  /*一氧化碳*/
            "NO2": "65",  /*二氧化氮*/
            "O3": "28",    /*臭氧*/
            "SO2": "41",  /*二氧化硫*/
            "time": "2014-12-26 11:48:40"/*更新时间*/  
        }
    ],
    "error_code": 0
}

实例:JSONDemo
运行效果:

代码清单:
布局文件:activity_main.xml
[html]  view plain  copy
  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=".MainActivity" >  
  7.   
  8.     <LinearLayout   
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="wrap_content"   
  11.         android:orientation="horizontal" >  
  12.   
  13.         <TextView  
  14.             android:layout_width="wrap_content"  
  15.             android:layout_height="wrap_content"  
  16.             android:layout_weight="1"  
  17.             android:gravity="center"  
  18.             android:text="城市:"  
  19.             android:textSize="23sp" />  
  20.   
  21.         <EditText   
  22.             android:id="@+id/city"  
  23.             android:layout_width="wrap_content"  
  24.             android:layout_height="wrap_content"  
  25.             android:layout_weight="3"  
  26.             android:inputType="text" />"  
  27.     </LinearLayout>  
  28.   
  29.     <Button  
  30.         android:id="@+id/query"  
  31.         android:layout_width="match_parent"  
  32.         android:layout_height="wrap_content"   
  33.         android:text="查询"   
  34.         android:textSize="23sp" />  
  35.       
  36.     <TextView  
  37.         android:id="@+id/result"  
  38.         android:layout_width="match_parent"  
  39.         android:layout_height="match_parent" />  
  40. </LinearLayout>  

Java源代码文件:MainActivity.java
[java]  view plain  copy
  1. package com.rainsong.jsondemo;  
  2.   
  3. import android.os.Bundle;  
  4. import android.app.Activity;  
  5. import android.view.Menu;  
  6. import android.view.View;  
  7. import android.view.View.OnClickListener;  
  8. import android.widget.Button;  
  9. import android.widget.EditText;  
  10. import android.widget.TextView;  
  11. import android.widget.Toast;  
  12.   
  13. public class MainActivity extends Activity {  
  14.     EditText et_city;  
  15.     Button btn_query;  
  16.     TextView tv_result;  
  17.     QueryTask task;  
  18.   
  19.     @Override  
  20.     protected void onCreate(Bundle savedInstanceState) {  
  21.         super.onCreate(savedInstanceState);  
  22.         setContentView(R.layout.activity_main);  
  23.   
  24.         et_city = (EditText)findViewById(R.id.city);  
  25.         tv_result = (TextView)findViewById(R.id.result);  
  26.         btn_query = (Button)findViewById(R.id.query);  
  27.   
  28.         btn_query.setOnClickListener(new OnClickListener() {  
  29.             public void onClick(View view) {  
  30.                 String city = et_city.getText().toString();  
  31.                 if (city.length() < 1) {  
  32.                     Toast.makeText(MainActivity.this"请输入城市名",  
  33.                             Toast.LENGTH_LONG).show();  
  34.                     return;  
  35.                 }  
  36.                 task = new QueryTask(MainActivity.this, tv_result);  
  37.                 task.execute(city);  
  38.             }  
  39.         });  
  40.     }  
  41.   
  42.     @Override  
  43.     public boolean onCreateOptionsMenu(Menu menu) {  
  44.         // Inflate the menu; this adds items to the action bar if it is present.  
  45.         getMenuInflater().inflate(R.menu.main, menu);  
  46.         return true;  
  47.     }  
  48.   
  49. }  

Java源代码文件:QueryTask.java
[java]  view plain  copy
  1. package com.rainsong.jsondemo;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.URLEncoder;  
  5. import java.util.ArrayList;  
  6.   
  7. import org.apache.http.HttpResponse;  
  8. import org.apache.http.NameValuePair;  
  9. import org.apache.http.client.HttpClient;  
  10. import org.apache.http.client.methods.HttpGet;  
  11. import org.apache.http.impl.client.DefaultHttpClient;  
  12. import org.apache.http.message.BasicNameValuePair;  
  13. import org.apache.http.util.EntityUtils;  
  14. import org.json.JSONArray;  
  15. import org.json.JSONException;  
  16. import org.json.JSONObject;  
  17.   
  18. import android.content.Context;  
  19. import android.os.AsyncTask;  
  20. import android.widget.TextView;  
  21. import android.widget.Toast;  
  22.   
  23. public class QueryTask extends AsyncTask<String, Void, String> {  
  24.     Context context;  
  25.     TextView tv_result;  
  26.   
  27.     private static final String JUHE_URL_ENVIRONMENT_AIR_PM =   
  28.                                     "http://web.juhe.cn:8080/environment/air/pm";  
  29.     private static final String JUHE_APPKEY = "你申请的APPKEY值";  
  30.   
  31.     public QueryTask(Context context, TextView tv_result) {  
  32.         // TODO Auto-generated constructor stub  
  33.         super();  
  34.         this.context = context;  
  35.         this.tv_result = tv_result;   
  36.     }  
  37.   
  38.     @Override  
  39.     protected String doInBackground(String... params) {  
  40.         String city = params[0];  
  41.   
  42.         ArrayList<NameValuePair> headerList = new ArrayList<NameValuePair>();  
  43.         headerList.add(new BasicNameValuePair("Content-Type""text/html; charset=utf-8"));  
  44.   
  45.         String targetUrl = JUHE_URL_ENVIRONMENT_AIR_PM;  
  46.   
  47.         ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();  
  48.         paramList.add(new BasicNameValuePair("key", JUHE_APPKEY));  
  49.         paramList.add(new BasicNameValuePair("dtype""json"));  
  50.         paramList.add(new BasicNameValuePair("city", city));  
  51.   
  52.         for (int i = 0; i < paramList.size(); i++) {  
  53.             NameValuePair nowPair = paramList.get(i);  
  54.             String value = nowPair.getValue();  
  55.             try {  
  56.                 value = URLEncoder.encode(value, "UTF-8");  
  57.             } catch (Exception e) {  
  58.             }  
  59.             if (i == 0) {  
  60.                 targetUrl += ("?" + nowPair.getName() + "=" + value);  
  61.             } else {  
  62.                 targetUrl += ("&" + nowPair.getName() + "=" + value);  
  63.             }  
  64.         }  
  65.   
  66.         HttpGet httpRequest = new HttpGet(targetUrl);  
  67.         try {  
  68.             for (int i = 0; i < headerList.size(); i++) {  
  69.                 httpRequest.addHeader(headerList.get(i).getName(),  
  70.                                         headerList.get(i).getValue());  
  71.             }  
  72.   
  73.             HttpClient httpClient = new DefaultHttpClient();  
  74.   
  75.             HttpResponse httpResponse = httpClient.execute(httpRequest);  
  76.             if (httpResponse.getStatusLine().getStatusCode() == 200) {  
  77.                 String strResult = EntityUtils.toString(httpResponse.getEntity());  
  78.                 return strResult;  
  79.             } else {  
  80.                 return null;  
  81.             }  
  82.         } catch (IOException e) {  
  83.             e.printStackTrace();  
  84.         }  
  85.         return null;  
  86.     }  
  87.   
  88.     @Override    
  89.     protected void onPostExecute(String result) {  
  90.         if (result != null) {  
  91.             try {  
  92.                 JSONObject jsonObject = new JSONObject(result);  
  93.                 int resultCode = jsonObject.getInt("resultcode");  
  94.                 if (resultCode == 200) {  
  95.                     JSONArray resultJsonArray = jsonObject.getJSONArray("result");  
  96.                     JSONObject resultJsonObject = resultJsonArray.getJSONObject(0);  
  97.                     String output = context.getString(R.string.city) + ": " + resultJsonObject.getString("city") + "\n"  
  98.                             + context.getString(R.string.PM25) + ": " + resultJsonObject.getString("PM2.5") + "\n"  
  99.                             + context.getString(R.string.AQI) + ": " + resultJsonObject.getString("AQI") + "\n"  
  100.                             + context.getString(R.string.quality) + ": " + resultJsonObject.getString("quality") + "\n"  
  101.                             + context.getString(R.string.PM10) + ": " + resultJsonObject.getString("PM10") + "\n"  
  102.                             + context.getString(R.string.CO) + ": " + resultJsonObject.getString("CO") + "\n"  
  103.                             + context.getString(R.string.NO2) + ": " + resultJsonObject.getString("NO2") + "\n"  
  104.                             + context.getString(R.string.O3) + ": " + resultJsonObject.getString("O3") + "\n"  
  105.                             + context.getString(R.string.SO2) + ": " + resultJsonObject.getString("SO2") + "\n"  
  106.                             + context.getString(R.string.time) + ": " + resultJsonObject.getString("time") + "\n";  
  107.                     tv_result.setText(output);  
  108.                 } else if (resultCode == 202) {  
  109.                     String reason = jsonObject.getString("reason");  
  110.                     tv_result.setText(reason);  
  111.                 } else {  
  112.                     Toast.makeText(context, "查询失败",  
  113.                             Toast.LENGTH_LONG).show();  
  114.                     tv_result.setText("");  
  115.                 }  
  116.             } catch (JSONException e) {  
  117.                 // TODO Auto-generated catch block  
  118.                 e.printStackTrace();  
  119.             }  
  120.         } else {  
  121.             Toast.makeText(context, "查询失败",  
  122.                                     Toast.LENGTH_LONG).show();  
  123.             tv_result.setText("");  
  124.         }  
  125.     }    
  126.     
  127. }  

字符串资源:string.xml

[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.   
  4.     <string name="app_name">JSONDemo</string>  
  5.     <string name="action_settings">Settings</string>  
  6.     <string name="hello_world">Hello world!</string>  
  7.   
  8.     <string name="city">城市</string>  
  9.     <string name="PM25">PM2.5指数</string>  
  10.     <string name="AQI">空气质量指数</string>  
  11.     <string name="quality">空气质量</string>  
  12.     <string name="PM10">PM10</string>  
  13.     <string name="CO">一氧化碳</string>  
  14.     <string name="NO2">二氧化氮</string>  
  15.     <string name="O3">臭氧</string>  
  16.     <string name="SO2">二氧化硫</string>  
  17.     <string name="time">更新时间</string>  
  18.       
  19. </resources>  

猜你喜欢

转载自blog.csdn.net/qq_39539367/article/details/80155248