Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 中的 Gson 用法:在 JSON 與 Java 結構間自由轉換

編輯:關於 Android 程式設計

Gson 是 Google 出品、在 Android 開發中廣泛使用的 JSON 處理庫。它能輕鬆地在 Java 物件與 JSON 字串之間雙向轉換,下面透過實例說明常見資料結構的處理方式。

一、把陣列、物件、List、Map 轉換成 JSON 字串

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class Main {
    public static class Student {
        private String name;
        int age;
        private String address;
        private Date dateOfBirth;

        public Student() { }

        public Student(String name, int age, String address, Date dateOfBirth) {
            this.name = name;
            this.age = age;
            this.address = address;
            this.dateOfBirth = dateOfBirth;
        }
        // 省略 getter / setter
    }

    public static void main(String[] args) {
        Gson gson = new Gson();

        /* 陣列轉成 JSON 串 */
        int[] numbers = {1, 1, 2, 3, 5, 8, 13};
        String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
        String numbersJson = gson.toJson(numbers);
        String daysJson = gson.toJson(days);

        /* List 轉成 JSON 串,元素為字串 */
        List names = new ArrayList();
        names.add("Alice");
        names.add("Bob");
        names.add("Carol");
        names.add("Mallory");
        String jsonNames = gson.toJson(names);

        /* List 轉成 JSON 串,元素為物件 */
        Student a = new Student("Alice", 20, "Apple St", new Date(2000, 10, 1));
        Student b = new Student("Bob", 23, "Banana St", null);
        Student c = new Student("Carol", 42, "Grape St", new Date(2000, 5, 21));
        Student d = new Student("Mallory", 24, "Mango St", null);
        List students = new ArrayList();
        students.add(a);
        students.add(b);
        students.add(c);
        students.add(d);
        String jsonStudents = gson.toJson(students);

        // 把 JSON 串還原成 Student 物件的集合
        Type type = new TypeToken>(){}.getType();
        List studentList = gson.fromJson(jsonStudents, type);
        for (Student student : studentList) {
            System.out.println("student.getName() = " + student.getName());
        }

        /* Map 轉成 JSON 串,value 為字串 */
        Map colors = new HashMap();
        colors.put("BLACK", "#000000");
        colors.put("RED", "#FF0000");
        colors.put("GREEN", "#008000");
        colors.put("BLUE", "#0000FF");
        colors.put("YELLOW", "#FFFF00");
        colors.put("WHITE", "#FFFFFF");
        String jsonmap = gson.toJson(colors);

        // 把 JSON 串還原成 Map
        Type type1 = new TypeToken>(){}.getType();
        Map map = gson.fromJson(jsonmap, type1);

        /* Map 轉成 JSON 串,value 為物件 */
        Map studentmap = new HashMap();
        studentmap.put("Alice", a);
        studentmap.put("Bob", b);
        studentmap.put("Carol", c);
        studentmap.put("Mallory", d);
        String jsonmap1 = gson.toJson(studentmap);

        Type type11 = new TypeToken>(){}.getType();
        Map map1 = gson.fromJson(jsonmap1, type11);
        for (String key : map1.keySet()) {
            System.out.println("map1.get = " + map1.get(key).getName());
        }
    }
}

執行後可觀察到以下規律:

1、單個物件(Object)對應的 JSON 串是一個 JsonObject,冒號「:」前是 Java 物件的變數名,冒號後則是變數值。

2、陣列與 List 對應的 JSON 串是一個 JsonArray。

3、Map 對應的 JSON 串也是 JsonObject,冒號前是 Map 的 Key,冒號後是 Map 的 Value。

二、把 JSON 串轉換成 Java 物件

關鍵在於判斷冒號「:」後 Value 的資料型別,對應到 Java 物件的欄位型別即可。以下是一段典型的後端回傳資料:

{
  "success": true,
  "data": {
    "list": [
      {"dataType": 0, "distance": 435.24, "isFav": 0, "parkCode": "0270000558",
       "parkName": "武漢金融港路場", "parkID": 558, "remark": "", "parkType": 0,
       "responsible": "", "responseTel": "13297062676", "consultTel": "",
       "coordinateX": 114.428102, "coordinateY": 30.462254, "coordinateEntrance": "",
       "rateInfo": "工作日", "introduce": "", "appState": 3, "paymentNoticeMinute": 0,
       "rentCount": 0, "rentSwitch": 0, "spaceCount": 42, "totalCount": 42,
       "imageName": "", "fullImage": "", "unitFee": 0.0, "unit": 0, "isRoadSide": 0,
       "rentOvertimeTimes": 0.0, "reservationKeepTime": 0, "supportPayType": 0,
       "address": "光谷大道金融港", "state": 1}
    ]
  }
}

對應的 Park 資料類只需按欄位型別宣告屬性即可:

package com.hust.map;

public class Park {
    int dataType;
    int rentCount;
    int parkCode;
    String parkName;          // 停車場名字
    int parkID;
    String remark;
    int parkType;
    String responsible;
    String responseTel;
    String consultTel;
    double coordinateX;       // 經度
    double coordinateY;       // 緯度
    String coordinateEntrance;
    String rateInfo;          // 收費標準
    String introduce;
    int appState;
    int paymentNoticeMinute;
    int spaceCount;           // 可租車位
    int totalCount;           // 總車位
    String imageName;
    String fullImage;
    int reservationKeepTime;
    int isRoadSide;
    double rentOvertimeTimes;
    double unitFee;
    int unit;
    int rentSwitch;
    int supportPayType;
    int isFav;
    double distance;          // 距離
    String address;           // 地址
    int state;
    // 省略 constructor 與 getter / setter
}

由於最外層的 data 是一個包含 list 陣列的結構,可用 HashMap 承接,再取出其中的列表:

package com.hust.map;

import java.util.ArrayList;
import java.util.HashMap;

public class DataFromNetWork {
    boolean success;
    HashMap> data;
}
DataFromNetWork mDataFromNetWork = mGson.fromJson(mParksString, DataFromNetWork.class);
ArrayList mParksList = mDataFromNetWork.data.get("list");

掌握以上要領,就能在 Gson 的協助下,於 JSON 與各種 Java 資料結構之間輕鬆穿梭。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved