Search…

Thao Tác với JSON trong Android

13/11/20207 min read
Sử dụng JSON trong Android để giao tiếp và lưu trữ dữ liệu.

Trong quá trình phát triển ứng dụng sẽ cần lưu trữ dữ liệu hoặc cần giao tiếp, truyền nhận dữ liệu từ nhiều thiết bị, việc chuyển đổi dữ liệu thành dạng văn bản sẽ giúp thuận tiện cho quán trình này.

Để hỗ trợ cho điều này JSON ra đời, ngoài ra còn có nhiều phương pháp chuyển đổi sang nhiều loại cấu trúc với cú pháp khác nhau như XML hoặc mỗi ngôn ngữ lập trình có thể hỗ trợ riêng cách thức của ngôn ngữ đó.

JSON là gì?

JSON là tên viết tắt của JavaScript Object Notation, là 1 chuẩn để lưu trữ và chuyển đổi dữ liệu và thuận tiện, JSON rất dễ đọc và dễ phân tích.

Cấu trúc của JSON

Cấu trúc của JSON, được bắt đầu bằng kí tự { và kết thúc bằng kí tự }. Trong { ... } sẽ định nghĩa những đối tượng.

Ví dụ định nghĩa 1 đối tượng Employee có tên là "Khoa" và họ là "Vo" thì chuỗi JSON được biểu diễn như sau:

{"firstName": "Khoa", "lastName": "Vo"}

Biểu diễn danh sách các employees:

{employees: [
    {"firstName": "John", "lastName": "Doe"},
    {"firstName": "Anna", "lastName": "Smith"},
    {"firstName": "Peter", "lastName": "Jones"}
]}

So sánh với cấu trúc XML:

<employees>
    <employee>
        <firstName>John</firstName>
        <lastName>Doe</lastName>
    </employee>
    <employee>
        <firstName>Anna</firstName>
        <lastName>Smith</lastName>
    </employee>
    <employee>
        <firstName>Peter</firstName>
        <lastName>Jones</lastName>
    </employee>
</employees>

Hay 1 chuỗi JSON phức tạp sẽ sử dụng để parse trong bài viết này là:

{"widget": {
     "debug": "on",
     "window": {
         "title": "Sample Konfabulator Widget",
         "name": "main_window",
         "width": 500,
         "height": 500
     },
     "image": { 
         "src": "Images/Sun.png",
         "name": "sun1",
         "hOffset": 250,
         "vOffset": 250,
         "alignment": "center"
     },
     "text": {
         "data": "Click Here",
         "size": 36,
         "style": "bold",
         "name": "text1",
         "hOffset": 250,
         "vOffset": 100,
         "alignment": "center",
         "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
     }
}}

Cấu trúc biểu diễn bằng XML:

<widget>
     <debug>on</debug>
     <window title="Sample Konfabulator Widget">
         <name>main_window</name>
         <width>500</width>
         <height>500</height>
     </window>
     <image src="Images/Sun.png" name="sun1">
         <hOffset>250</hOffset>
         <vOffset>250</vOffset>
         <alignment>center</alignment>
     </image>
     <text data="Click Here" size="36" style="bold">
         <name>text1</name>
         <hOffset>250</hOffset>
         <vOffset>100</vOffset>
         <alignment>center</alignment>
         <onMouseUp>
             sun1.opacity = (sun1.opacity / 100) * 90;
         </onMouseUp>
     </text>
</widget>

Biểu diễn 1 nội dung như nhau nhưng JSON gọn hơn XML, so sánh về tốc độ parse thì JSON nhanh hơn rất nhiều so với XML.

Thao tác với JSON trong Android

Trong Android, các thư viện dùng để thao tác với JSON nằm trong package org.json.

Đọc JSON trong Android

Cùng phân tích chuỗi JSON để parse  thành các đối tượng trong Java.

{"widget": {
     "debug": "on",
     "window": {
         "title": "Sample Konfabulator Widget",
         "name": "main_window",
         "width": 500,
         "height": 500
     },
     "image": { 
         "src": "Images/Sun.png",
         "name": "sun1",
         "hOffset": 250,
         "vOffset": 250,
         "alignment": "center"
     },
     "text": {
         "data": "Click Here",
         "size": 36,
         "style": "bold",
         "name": "text1",
         "hOffset": 250,
         "vOffset": 100,
         "alignment": "center",
         "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
     }
}}

Có tất cả 4 đối tượng:

  1. widget: có thuộc tính là debug giá trị on và 3 thuộc tính khác là 3 đối tượng window, image, text.
  2. window: có các thuộc tính là title, name, width, height.
  3. image: có các thuộc tính là src, name, hOffset, vOffset, alignment.
  4. text: có các thuộc tính là data, size, style, name,  hOffset, vOffset, alignment, onMouseUp.

Các bước parse như sau:

Bước 1: tạo đối tượng JSONObject với đối số truyền vào là chuỗi JSON trên.

String json =   "{\"widget\": {\n" +
                "     \"debug\": \"on\",\n" +
                "     \"window\": {\n" +
                "          \"title\": \"Sample Konfabulator Widget\",\n" +
                "          \"name\": \"main_window\",\n" +
                "          \"width\": 500,\n" +
                "          \"height\": 500\n" +
                "     },\n" +
                "     \"image\": { \n" +
                "          \"src\": \"Images/Sun.png\",\n" +
                "          \"name\": \"sun1\",\n" +
                "          \"hOffset\": 250,\n" +
                "          \"vOffset\": 250,\n" +
                "          \"alignment\": \"center\"\n" +
                "     },\n" +
                "     \"text\": {\n" +
                "          \"data\": \"Click Here\",\n" +
                "          \"size\": 36,\n" +
                "          \"style\": \"bold\",\n" +
                "          \"name\": \"text1\",\n" +
                "          \"hOffset\": 250,\n" +
                "          \"vOffset\": 100,\n" +
                "          \"alignment\": \"center\",\n" +
                "          \"onMouseUp\": \"sun1.opacity = (sun1.opacity / 100) * 90;\"\n" +
                "     }\n" +
                "}}";
try {
    JSONObject rootObject = new JSONObject(json);
} catch (JSONException e) {
    e.printStackTrace();
}

Bước 2: lấy JSONObject widget.

JSONObject widgetObject = rootObject.getJSONObject("widget");

Bước 3: Lấy ra tất các thuộc tính, nếu là 1 đối tượng thì phải tạo JSONObject và lấy thuộc tính bởi các phương thức:

  • int getInt(String name)
  • double getDouble(String name)
  • boolean getBoolean(String name)
  • String getString(String name)
  • long getLong(String name)
  • Object get(String name)

Lấy thuộc tính debug của widget:

String debug = widgetObject.getString("debug");

Lấy thuộc tính window của widget:

JSONObject windowObject = widgetObject.getJSONObject("window");
String window_title = windowObject.getString("title");
String window_name = windowObject.getString("name");
int window_height = windowObject.getInt("height");
int window_width = windowObject.getInt("width");

Lấy thuộc tính image của widget:

JSONObject imageObject = widgetObject.getJSONObject("image");
String image_src = imageObject.getString("src");
String image_name = imageObject.getString("name");
int image_hOffset = imageObject.getInt("hOffset");
int image_vOffset = imageObject.getInt("vOffset");
String image_alignment = imageObject.getString("alignment");

Lấy thuộc tính text của widget:

JSONObject textObject = widgetObject.getJSONObject("text");
String text_data = textObject.getString("data");
String text_size = textObject.getString("size");
String text_style = textObject.getString("style");
String text_name = textObject.getString("name");
int text_hOffset = textObject.getInt("hOffset");
int text_vOffset = textObject.getInt("vOffset");
String text_alignment = textObject.getString("alignment");
String text_on_mouseup = textObject.getString("onMouseUp");

Và dưới đây là mã đầy đủ của ví dụ trên:

String json =  "{\"widget\": {\n" +
               "     \"debug\": \"on\",\n" +
               "     \"window\": {\n" +
               "          \"title\": \"Sample Konfabulator Widget\",\n" +
               "          \"name\": \"main_window\",\n" +
               "          \"width\": 500,\n" +
               "          \"height\": 500\n" +
               "     },\n" +
               "     \"image\": { \n" +
               "          \"src\": \"Images/Sun.png\",\n" +
               "          \"name\": \"sun1\",\n" +
               "          \"hOffset\": 250,\n" +
               "          \"vOffset\": 250,\n" +
               "          \"alignment\": \"center\"\n" +
               "     },\n" +
               "     \"text\": {\n" +
               "          \"data\": \"Click Here\",\n" +
               "          \"size\": 36,\n" +
               "          \"style\": \"bold\",\n" +
               "          \"name\": \"text1\",\n" +
               "          \"hOffset\": 250,\n" +
               "          \"vOffset\": 100,\n" +
               "          \"alignment\": \"center\",\n" +
               "          \"onMouseUp\": \"sun1.opacity = (sun1.opacity / 100) * 90;\"\n" +
               "     }\n" +
               "}}";
try {
    JSONObject rootObject = new JSONObject(json);
    JSONObject widgetObject = rootObject.getJSONObject("widget");
    String debug = widgetObject.getString("debug");
    JSONObject windowObject = widgetObject.getJSONObject("window");
    String window_title = windowObject.getString("title");
    String window_name = windowObject.getString("name");
    int window_height = windowObject.getInt("height");
    int window_width = windowObject.getInt("width");
    JSONObject imageObject = widgetObject.getJSONObject("image");
    String image_src = imageObject.getString("src");
    String image_name = imageObject.getString("name");
    int image_hOffset = imageObject.getInt("hOffset");
    int image_vOffset = imageObject.getInt("vOffset");
    String image_alignment = imageObject.getString("alignment");
    JSONObject textObject = widgetObject.getJSONObject("text");
    String text_data = textObject.getString("data");
    String text_size = textObject.getString("size");
    String text_style = textObject.getString("style");
    String text_name = textObject.getString("name");
    int text_hOffset = textObject.getInt("hOffset");
    int text_vOffset = textObject.getInt("vOffset");
    String text_alignment = textObject.getString("alignment");
    String text_on_mouseup = textObject.getString("onMouseUp");
} catch (JSONException e) {
    e.printStackTrace();
}

Tiếp theo parse 1 chuỗi JSON dưới đây:

{"employees": [
     {"firstName": "John", "lastName": "Doe"},
     {"firstName": "Anna", "lastName": "Smith"},
     {"firstName": "Peter", "lastName": "Jones"}
]}

Mã nguồn parse:

String json = "{\"employees\":[\n" +
                   "     {\"firstName\":\"John\", \"lastName\":\"Doe\"},\n" +
                   "     {\"firstName\":\"Anna\", \"lastName\":\"Smith\"},\n" +
                   "     {\"firstName\":\"Peter\", \"lastName\":\"Jones\"}\n" +
                   "]}";
try {
    JSONObject rootObject = new JSONObject(json);
    JSONArray employeesArray = rootObject.getJSONArray("employees");
    for(int i = 0; i < employeesArray.length(); i++) {
        JSONObject employeeObject = employeesArray.getJSONObject(i);
        String firstName = employeeObject.getString("firstName");
        String lastName = employeeObject.getString("lastname");
    }
} catch (JSONException e) {
    e.printStackTrace();
}

Lấy về danh sách các đối tượng thông qua phương thức getJSONArray(String name).

Phương thức này trả về 1 JSONArray.

Qua từng phần tử trong danh sách và lấy ra các giá trị của các thuộc tính.

Ghi JSON trong Android

Tạo 1 class City như sau:

public class City {
    private String mName;
    private LatLng mPos;

    public City(String name, LatLng pos){
        mName = name;
        mPos = pos;
    }

    public String getName() {
        return mName;
    }

    public LatLng getPos() {
        return mPos;
    }

    public void setName(String name) {
        this.mName = name;
    }

    public void setPos(LatLng pos) {
        this.mPos = pos;
    }
}

Lớp LatLng mô tả latitude và longtitute của City:

public class LatLng {
     private double mLat;
     private double mLng;

     public LatLng(){
     }

     public LatLng(double lat, double lng) {
         mLat = lat;
         mLng = lng;
     }

     public void setLat(double lat) {
          this.mLat = lat;
     }

     public void setLng(double lng) {
          this.mLng = lng;
     }

     public double getLat() {
         return mLat;
     }

     public double getLng() {
         return mLng;
     }
}

Override lại phương thức toString() của lớp City để chuyển thành chuỗi JSON như sau:

@Override
public String toString() {
    JSONObject jsonCity = new JSONObject();
    JSONObject jsonLatLng = new JSONObject();

    try {
        jsonLatLng.put("lat", mPos.getLat());
        jsonLatLng.put("lng", mPos.getLng());

        jsonCity.put("name", mName);
        jsonCity.put("latlng", jsonLatLng);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return jsonCity.toString();
}
City city = new City("Ho Chi Minh", new LatLng(10.887469,106.790446));
Log.d("JsonWorking", "onCreate: " + city.toString());

Và được kết quả:

D/JsonWorking: onCreate: {"latlng":{"lng":106.790446,"lat":10.887469},"name":"Ho Chi Minh"}

Download source code đầy đủ:

IO Stream

IO Stream Co., Ltd

30 Trinh Dinh Thao, Hoa Thanh ward, Tan Phu district, Ho Chi Minh city, Vietnam
+84 28 22 00 11 12
developer@iostream.co

383/1 Quang Trung, ward 10, Go Vap district, Ho Chi Minh city
Business license number: 0311563559 issued by the Department of Planning and Investment of Ho Chi Minh City on February 23, 2012

©IO Stream, 2013 - 2024