Thứ Hai, 15 tháng 10, 2018

Android - Trình phân tích cú pháp JSON

JSON là viết tắt của JavaScript Object Notation.It là một định dạng trao đổi dữ liệu độc lập và là lựa chọn thay thế tốt nhất cho XML. Chương này giải thích cách phân tích cú pháp tệp JSON và trích xuất thông tin cần thiết từ nó.

Android cung cấp bốn lớp khác nhau để thao tác dữ liệu JSON. Các lớp này là JSONArray, JSONObject, JSONStringer và JSONTokenizer

Học lập trình Android. Bước đầu tiên là xác định các trường trong dữ liệu JSON mà bạn quan tâm. Ví dụ: Trong JSON đưa ra dưới đây, chúng tôi chỉ muốn nhận nhiệt độ.
{
   "sys":
   {
      "country":"GB",
      "sunrise":1381107633,
      "sunset":1381149604
   },
   "weather":[
      {
         "id":711,
         "main":"Smoke",
         "description":"smoke",
         "icon":"50n"
      }
   ],
 
  "main":
   {
      "temp":304.15,
      "pressure":1009,
   }
}

JSON - Thành phần

Tệp JSON bao gồm nhiều thành phần. Đây là bảng xác định các thành phần của một tệp JSON và mô tả của chúng
Sr.NoThành phần & mô tả
1Mảng([)

Trong tệp JSON, dấu ngoặc vuông ([) đại diện cho một mảng JSON
2Các đối tượng({)
Trong một tệp JSON, dấu ngoặc nhọn ({) đại diện cho một đối tượng JSON
3Chìa khóa

Một đối tượng JSON chứa một khóa chỉ là một chuỗi. Các cặp khóa / giá trị tạo thành một đối tượng JSON
4Giá trị

Mỗi khóa có một giá trị có thể là chuỗi, số nguyên hoặc gấp đôi v.v ...

JSON - Phân tích cú pháp

Để phân tích một đối tượng JSON, chúng ta sẽ tạo một đối tượng lớp JSONObject và chỉ định một chuỗi chứa dữ liệu JSON cho nó. Cú pháp của nó là

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

Bước cuối cùng là phân tích cú pháp JSON. Một tệp JSON bao gồm các đối tượng khác nhau với cặp khóa / giá trị khác nhau vv Vì vậy, JSONObject có một hàm riêng biệt để phân tích cú pháp từng thành phần của tệp JSON. Cú pháp của nó được đưa ra dưới đây
JSONObject sys  = reader.getJSONObject("sys");
country = sys.getString("country");
   
JSONObject main  = reader.getJSONObject("main");
temperature = main.getString("temp");
Phương thức getJSONObject trả về đối tượng JSON. Phương thức getStringtrả về giá trị chuỗi của khóa được chỉ định.

Ngoài các phương thức này, còn có các phương thức khác được lớp này cung cấp để phân tích cú pháp các tệp JSON tốt hơn. Những phương pháp này được liệt kê dưới đây

Sr.NoPhương pháp & mô tả
1get (Tên chuỗi)

Phương thức này chỉ trả về giá trị nhưng ở dạng kiểu đối tượng
2getBoolean (Tên chuỗi)
Phương thức này trả về giá trị boolean được chỉ định bởi khóa
3getDouble (Tên chuỗi)
Phương thức này trả về giá trị kép được chỉ định bởi khóa
4getInt (Tên chuỗi)
Phương thức này trả về giá trị nguyên được chỉ định bởi khóa
5getLong (Tên chuỗi)

Phương thức này trả về giá trị dài được chỉ định bởi khóa
6chiều dài()
Phương thức này trả về số lượng ánh xạ tên / giá trị trong đối tượng này ..
7tên ()

Phương thức này trả về một mảng chứa các tên chuỗi trong đối tượng này.

Thí dụ

Để thử nghiệm với ví dụ này, bạn có thể chạy nó trên một thiết bị thực tế hoặc trong một trình giả lập.

Các bướcSự miêu tả
1Bạn sẽ sử dụng Android studio để tạo ứng dụng Android.
2Sửa đổi tệp src / MainActivity.java để thêm mã cần thiết.
3Sửa đổi res / layout / activity_main để thêm các thành phần XML tương ứng
4Sửa đổi res / values ​​/ string.xml để thêm các thành phần chuỗi cần thiết
5Chạy ứng dụng và chọn thiết bị Android đang chạy và cài đặt ứng dụng trên đó và xác minh kết quả
Sau đây là nội dung của tệp hoạt động chính đã sửa đổi 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);
      }
   }
}
Sau đây là nội dung sửa đổi của 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();
   }
}
Sau đây là nội dung sửa đổi của 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>
Sau đây là nội dung sửa đổi của 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>
Sau đây là nội dung của tệp 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>
Hãy thử chạy ứng dụng của chúng tôi, chúng tôi vừa sửa đổi. Tôi cho rằng bạn đã tạo AVD của mình trong khi thiết lập môi trường.

Để chạy ứng dụng từ Android studio, hãy mở một trong các tệp hoạt động của dự án của bạn và nhấp vào biểu tượng Chạy từ thanh công cụ.

Android studio cài đặt ứng dụng trên AVD của bạn và khởi động ứng dụng và nếu mọi thứ đều ổn với thiết lập và ứng dụng của bạn, ứng dụng sẽ hiển thị cửa sổ Trình mô phỏng sau

học lập trình Android
Ví dụ trên cho thấy dữ liệu từ chuỗi json, Dữ liệu đã chứa thông tin chi tiết về nhà tuyển dụng cũng như thông tin về lương.

Không có nhận xét nào:

Đăng nhận xét

Lập trình Android - RenderScript

Trong chương này, chúng ta sẽ tìm hiểu về Android RenderScript. Thông thường các ứng dụng trên Android được thiết kế để tiêu thụ tài nguyên ...