Android平台自带了JSON解析的相关API,可以将文件、输入流中的数据转化为JSON对象,然后从对象中获取JSON保存的数据内容。
<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>
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; } }
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-8")); 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-8"); } 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") + "\n" + context.getString(R.string.PM25) + ": " + resultJsonObject.getString("PM2.5") + "\n" + context.getString(R.string.AQI) + ": " + resultJsonObject.getString("AQI") + "\n" + context.getString(R.string.quality) + ": " + resultJsonObject.getString("quality") + "\n" + context.getString(R.string.PM10) + ": " + resultJsonObject.getString("PM10") + "\n" + context.getString(R.string.CO) + ": " + resultJsonObject.getString("CO") + "\n" + context.getString(R.string.NO2) + ": " + resultJsonObject.getString("NO2") + "\n" + context.getString(R.string.O3) + ": " + resultJsonObject.getString("O3") + "\n" + context.getString(R.string.SO2) + ": " + resultJsonObject.getString("SO2") + "\n" + context.getString(R.string.time) + ": " + resultJsonObject.getString("time") + "\n"; 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-8"?> <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指数</string> <string name="AQI">空气质量指数</string> <string name="quality">空气质量</string> <string name="PM10">PM10</string> <string name="CO">一氧化碳</string> <string name="NO2">二氧化氮</string> <string name="O3">臭氧</string> <string name="SO2">二氧化硫</string> <string name="time">更新时间</string> </resources>
Returns the value at index if it exists and is a JSONObject.
原文地址:http://blog.csdn.net/hantangsongming/article/details/42234293