- Android 基础
- Android - 首页
- Android - 概述
- Android - 环境设置
- Android - 架构
- Android - 应用组件
- Android - Hello World 例子
- Android - 资源
- Android - 活动 (Activities)
- Android - 服务 (Services)
- Android - 广播接收器 (Broadcast Receivers)
- Android - 内容提供器 (Content Providers)
- Android - 片段 (Fragments)
- Android - 意图/过滤器 (Intents/Filters)
- Android - 用户界面
- Android - UI 布局
- Android - UI 控件
- Android - 事件处理
- Android - 样式和主题
- Android - 自定义组件
- Android 高级概念
- Android - 拖放
- Android - 通知
- 基于位置的服务
- Android - 发送邮件
- Android - 发送短信
- Android - 电话呼叫
- 发布 Android 应用
- Android 有用示例
- Android - 警报对话框
- Android - 动画
- Android - 音频捕捉
- Android - AudioManager
- Android - 自动完成
- Android - 最佳实践
- Android - 蓝牙
- Android - 相机
- Android - 剪贴板
- Android - 自定义字体
- Android - 数据备份
- Android - 开发者工具
- Android - 模拟器
- Android - Facebook 集成
- Android - 手势
- Android - Google 地图
- Android - 图片效果
- Android - ImageSwitcher
- Android - 内部存储
- Android - JetPlayer
- Android - JSON 解析器
- Android - LinkedIn 集成
- Android - 加载 Spinne
- Android - 本地化
- Android - 登录屏幕
- Android - MediaPlayer
- Android - 多点触控
- Android - 导航
- Android - 网络连接
- Android - NFC 指南
- Android - PHP/MySQL
- Android - 进度圆圈
- Android - ProgressBar
- Android - 推送通知
- Android - RenderScript
- Android - RSS 阅读器
- Android - 屏幕录制
- Android - SDK 管理器
- Android - 传感器
- Android - 会话管理
- Android - Shared Preferences
- Android - SIP 协议
- Android - 拼写检查器
- Android - SQLite 数据库
- Android - 支持库
- Android - 测试
- Android - 文本转语音
- Android - TextureView
- Android - Twitter 集成
- Android - UI 设计
- Android - UI 模式
- Android - UI 测试
- Android - WebView 布局
- Android - Wi-Fi
- Android - 小部件 (Widgets)
- Android - XML 解析器
- Android 有用资源
- Android - 问答
- Android - 有用资源
- Android - 讨论
Android - JSON 解析器
JSON 代表 JavaScript 对象表示法 (JavaScript Object Notation)。它是一种独立的数据交换格式,是 XML 的最佳替代方案。本章解释如何解析 JSON 文件并从中提取必要信息。
Android 提供四个不同的类来操作 JSON 数据。这些类是 **JSONArray、JSONObject、JSONStringer 和 JSONTokenizer**。
第一步是确定您感兴趣的 JSON 数据中的字段。例如,在下面的 JSON 中,我们只对获取温度感兴趣。
{
"sys":
{
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],
"main":
{
"temp":304.15,
"pressure":1009,
}
}
JSON - 元素
JSON 文件包含许多组件。以下是定义 JSON 文件组件及其描述的表格:
| 序号 | 组件及描述 |
|---|---|
| 1 | 数组([]) 在 JSON 文件中,方括号([])表示 JSON 数组。 |
| 2 | 对象({}) 在 JSON 文件中,花括号({})表示 JSON 对象。 |
| 3 | 键 (Key) JSON 对象包含一个键,它只是一个字符串。键/值对构成一个 JSON 对象。 |
| 4 | 值 (Value) 每个键都有一个值,可以是字符串、整数或双精度数等。 |
JSON - 解析
为了解析 JSON 对象,我们将创建一个 JSONObject 类的对象,并向其指定包含 JSON 数据的字符串。其语法如下:
String in; JSONObject reader = new JSONObject(in);
最后一步是解析 JSON。JSON 文件由不同的对象组成,这些对象具有不同的键/值对等。因此,JSONObject 具有一个单独的函数来解析 JSON 文件的每个组件。其语法如下:
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
方法 **getJSONObject** 返回 JSON 对象。方法 **getString** 返回指定键的字符串值。
除了这些方法外,此类还提供了其他方法以更好地解析 JSON 文件。这些方法列在下面:
| 序号 | 方法及描述 |
|---|---|
| 1 | get(String name) 此方法只返回对象类型的值。 |
| 2 | getBoolean(String name) 此方法返回键指定的布尔值。 |
| 3 | getDouble(String name) 此方法返回键指定的双精度值。 |
| 4 |
getInt(String name)
此方法返回键指定的整数值。 |
| 5 | getLong(String name) 此方法返回键指定的长整数值。 |
| 6 | length() 此方法返回此对象中名称/值映射的数量。 |
| 7 | names() 此方法返回一个包含此对象中字符串名称的数组。 |
示例
要试验此示例,您可以在实际设备或模拟器上运行它。
| 步骤 | 描述 |
|---|---|
| 1 | 您将使用 Android Studio 创建一个 Android 应用。 |
| 2 | 修改 src/MainActivity.java 文件以添加必要的代码。 |
| 3 | 修改 res/layout/activity_main 以添加相应的 XML 组件。 |
| 4 | 修改 res/values/strings.xml 以添加必要的字符串组件。 |
| 5 | 运行应用程序,选择正在运行的 Android 设备,将应用程序安装到该设备上,并验证结果。 |
以下是修改后的主活动文件 **src/MainActivity.java** 的内容。
package com.example.tutorialspoint7.myapplication;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this,"Json Data is
downloading",Toast.LENGTH_LONG).show();
}
@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://api.androidhive.info/contacts/";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList,
R.layout.list_item, new String[]{ "email","mobile"},
new int[]{R.id.email, R.id.mobile});
lv.setAdapter(adapter);
}
}
}
以下是修改后的 xml 文件 **HttpHandler.java** 的内容。
package com.example.tutorialspoint7.myapplication;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
以下是修改后的 xml 文件 **res/layout/activity_main.xml** 的内容。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context="com.example.tutorialspoint7.myapplication.MainActivity">
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
以下是修改后的 xml 文件 **res/layout/list_item.xml** 的内容。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="@dimen/activity_horizontal_margin">
<TextView
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="@color/colorAccent" />
<TextView
android:id="@+id/mobile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold" />
</LinearLayout>
以下是 **AndroidManifest.xml** 文件的内容。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint7.myapplication">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
让我们尝试运行我们刚刚修改的应用程序。我假设您在进行环境设置时已经创建了您的 **AVD**。要从 Android Studio 运行该应用,请打开项目中的一个活动文件,然后点击工具栏中的运行
图标。Android Studio 将应用安装到您的 AVD 并启动它,如果您的设置和应用程序一切正常,它将显示以下模拟器窗口:
上面的示例显示了来自字符串 json 的数据,数据包含雇员详细信息以及薪资信息。
