开发手册 欢迎您!
软件开发者资料库

Android - JSON Parser

Android JSON Parser - 学习Android编程以及如何从环境设置,应用程序组件,活动生命周期,服务生命周期,应用程序架构,发布应用程序,调试应用程序,处理事件,布局,菜单,用户界面控件开始开发Android手机和ipad应用程序,样式和主题,处理轮换,字体管理,发送电子邮件,数据存储,管理媒体,发送短信,电话。

JSON代表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文件组件的表及其描述 :

Sr.NoComponent & description
1

Array([])

在JSON文件中,方括号([)表示JSON数组

2

Objects({})

在JSON文件中,花括号({)表示JSON对象

3

Key

JSON对象包含一个只是字符串的键.键/值对构成一个JSON对象

4

Value

每个键的值都可以是字符串,整数或双倍等等

JSON  - 解析

为了解析JSON对象,我们将创建一个类JSONObject的对象,并指定一个包含JSON数据的字符串.它的语法是 :

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


最后一步是解析JSON. JSON文件由具有不同键/值对e.t.c的不同对象组成.所以JSONObject有一个单独的函数来解析JSON文件的每个组件.它的语法在下面和下面给出;

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


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

除了这些方法之外,此类还提供了其他方法来更好地解析JSON文件.这些方法列在下面 :

Sr .NoMethod & description
1

get(String name)

此方法只返回值,但采用对象类型的形式

2

getBoolean(String name)

此方法返回键指定的布尔值

3

getDouble(String name)

此方法返回键指定的double值

4 getInt(String name)

此方法返回键指定的整数值

5

getLong(String name)

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

6

length()

此方法返回名称/值映射的数量这个对象..

7

names()

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

示例

要试验此示例,您可以运行这在实际设备或模拟器中.

步骤描述
1您将使用Android工作室创建Android应用程序.
2修改src/MainActivity.java文件以添加必要的代码.
3修改res/layout/activity_main添加相应的XML组件
4修改res/values/string.xml以添加必要的字符串组件
5运行应用程序并选择正在运行的Android设备并在其上安装应用程序并验证结果

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

package com.example.it13527.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> 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 {      @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 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.it13527.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 res/layout/list_item.xml的修改内容.

   Following is the modified content of the xml res/layout/list_item.xml.      


以下是 AndroidManifest.xml 文件的内容.

                                                                                 


让我们尝试运行我们刚修改过的应用程序.我假设您在进行环境设置时创建了 AVD .要从Android工作室运行应用程序,请打开项目的一个活动文件,然后单击运行Eclipse Run Icon icon从工具栏中. Android工作室在您的AVD上安装应用程序并启动它,如果您的设置和应用程序一切正常,它将显示以下模拟器窗口 :

Anroid XML Parser Tutorial

上面的示例显示了字符串json中的数据,该数据包含雇主详细信息以及工资信息.