Android JSON Parser怎么解析JSON数据?

文章导读
上一个 测验 下一个 JSON 是 JavaScript Object Notation 的缩写。它是一种独立的数据交换格式,是 XML 的最佳替代方案。本章将介绍如何解析 JSON 文件并从中提取必要信息。
📋 目录
  1. JSON - 元素
  2. JSON - 解析
  3. 示例
A A

Android - JSON 解析器



上一个
测验
下一个

JSON 是 JavaScript Object Notation 的缩写。它是一种独立的数据交换格式,是 XML 的最佳替代方案。本章将介绍如何解析 JSON 文件并从中提取必要信息。

Android 提供了四个不同的 class 来操作 JSON 数据。这些 class 是 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

JSON 对象包含一个键,它只是一个字符串。键/值对构成了 JSON 对象

4

每个键都有一个值,可以是字符串、整数或 double 等

JSON - 解析

要解析 JSON 对象,我们将创建一个 JSONObject class 的对象,并为其指定一个包含 JSON 数据的字符串。其语法如下 −

String in;
JSONObject reader = new JSONObject(in);

最后一步是解析 JSON。JSON 文件由不同的对象组成,每个对象有不同的键/值对等。因此,JSONObject 提供了单独的 function 来解析 JSON 文件的每个组件。其语法如下 −

JSONObject sys  = reader.getJSONObject("sys");
country = sys.getString("country");
			
JSONObject main  = reader.getJSONObject("main");
temperature = main.getString("temp");

getJSONObject 方法返回 JSON 对象。getString 方法返回指定键的字符串值。

除了这些方法外,该 class 还提供了其他方法来更好地解析 JSON 文件。这些方法列在下面 −

序号 方法 & 描述
1

get(String name)

此方法仅返回值,但以 Object 类型形式返回

2

getBoolean(String name)

此方法返回由键指定的 boolean 值

3

getDouble(String name)

此方法返回由键指定的 double 值

4 getInt(String name)

此方法返回由键指定的 integer 值

5

getLong(String name)

此方法返回由键指定的 long 值

6

length()

此方法返回此对象中名称/值映射的数量。

7

names()

此方法返回包含此对象中字符串名称的数组。

示例

要实验这个示例,你可以在实际设备上或在模拟器中运行。

步骤 描述
1 你将使用 Android Studio 创建一个 Android 应用程序。
2 修改 src/MainActivity.java 文件以添加必要的代码。
3 修改 res/layout/activity_main 以添加相应的 XML 组件
4 修改 res/values/string.xml 以添加必要的字符串组件
5 运行应用程序,选择一个运行中的 Android 设备并在该设备上安装应用程序,然后验证结果

以下是修改后的主活动文件 src/MainActivity.java 的内容。

package com.example.7.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 数据正在 
            下载中",Toast.LENGTH_LONG).show();

      }

      @Override
      protected Void doInBackground(Void... arg0) {
         HttpHandler sh = new HttpHandler();
         // 向 URL 发送请求并获取响应
         String url = "http://api.androidhive.info/contacts/";
         String jsonStr = sh.makeServiceCall(url);
      
         Log.e(TAG, "来自 URL 的响应: " + jsonStr);
         if (jsonStr != null) {
            try {
               JSONObject jsonObj = new JSONObject(jsonStr);
            
               // 获取 JSON Array 节点
               JSONArray contacts = jsonObj.getJSONArray("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 节点是 JSON 对象
                  JSONObject phone = c.getJSONObject("phone");
                  String mobile = phone.getString("mobile");
                  String home = phone.getString("home");
                  String office = phone.getString("office");

                  // 单个联系人的临时 hash map
                  HashMap<String, String> contact = new HashMap<>();

                  // 将每个子节点添加到 HashMap,键 => 值
                  contact.put("id", id);
                  contact.put("name", name);
                  contact.put("email", email);
                  contact.put("mobile", mobile);
               
                  // 将联系人添加到联系人列表
                  contactList.add(contact);
               }
            } catch (final JSONException e) {
               Log.e(TAG, "JSON 解析错误: " + e.getMessage());
               runOnUiThread(new Runnable() {
                  @Override
                  public void run() {
                     Toast.makeText(getApplicationContext(),
                     "JSON 解析错误: " + e.getMessage(),
                        Toast.LENGTH_LONG).show();
                  }
               });

            }
   
         } else {
            Log.e(TAG, "无法从服务器获取 JSON。");
            runOnUiThread(new Runnable() {
               @Override
               public void run() {
                  Toast.makeText(getApplicationContext(), 
                     "无法从服务器获取 JSON。请检查 LogCat 以查找可能的错误!", 
                     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.7.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");
         // 读取响应
         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.7.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.7.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 中运行应用,请打开项目的一个 activity 文件,然后点击工具栏中的运行 Eclipse Run Icon 图标。Android Studio 会在你的 AVD 上安装应用并启动它,如果你的设置和应用程序一切正常,它将显示以下模拟器窗口 −

Anroid XML Parser Tutorial

上面的示例显示了来自 string JSON 的数据,该数据包含了雇员详细信息以及薪资信息。