android JSON解析之JSONObject與GSON

推薦閱讀

TensorFlow 2.0 (八) - 強化學習 DQN 玩轉 gym Mountain Car
TensorFlow 2.0 (七) - 強化學習 Q-Learning 玩轉 OpenAI gym
TensorFlow 2.0 (六) - 監督學習玩轉 OpenAI gym game
TensorFlow 2.0 (五) - mnist手寫數字識別(CNN卷積神經網絡)
TensorFlow入門(四) - mnist手寫數字識別(製做h5py訓練集)
TensorFlow入門(三) - mnist手寫數字識別(可視化訓練)
TensorFlow入門(二) - mnist手寫數字識別(模型保存加載)
TensorFlow入門(一) - mnist手寫數字識別(網絡搭建)html

1.寫在前面

JSON數據是android網絡開發中常見的數據格式,JSON最多見的傳輸方法是使用HTTP協議,關於android開發中HTTP協議的使用方法可參考個人另外一篇隨筆android網絡編程之HTTP,解析JSON數據有多種方法:java

  • 使用官方自帶JSONObject
  • 使用第三方開源庫,包括但不限於GSONFastJSONJackson,本文主要介紹由Google提供的GSON庫的使用方法。

2.JSONObject的使用方法

2.1 示例代碼

//org.json.JSONArray;
    //org.json.JSONObject;
    private void parseJSONWithJSONObject(String jsonData){
        try {
            //將json字符串jsonData裝入JSON數組,即JSONArray
            //jsonData能夠是從文件中讀取,也能夠從服務器端得到
            JSONArray jsonArray = new JSONArray(jsonData);
            for (int i = 0; i< jsonArray.length(); i++) {
                //循環遍歷,依次取出JSONObject對象
                //用getInt和getString方法取出對應鍵值
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                int stu_no = jsonObject.getInt("stu_no");
                String stu_name = jsonObject.getString("stu_name");
                String stu_sex = jsonObject.getString("stu_sex");
                Log.d("MainActivity","stu_no: " + stu_no);
                Log.d("MainActivity","stu_name: " + stu_name);
                Log.d("MainActivity","stu_sex: " + stu_sex);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2.2 字符串jsonData以下,圖爲運行結果

[{ "stu_no":12345,"stu_name":"John","stu_sex":"male"
},{ "stu_no":12346,"stu_name":"Tom","stu_sex":"male"
},{"stu_no":12347,"stu_name":"Lily","stu_sex":"female"}]

parseJSON示例代碼

3.GSON的使用方法

3.1 下載並安裝

  • GSON2.6.1下載地址,點擊便可下載。
  • 將下載的gson-2.6.1.jar複製到項目目錄->app->libs文件夾下
    app/libs文件夾

3.2 方法簡介

  • toJson(params1),將傳入對象轉換爲字符串
  • fromJson(params1,params2),傳入兩個參數,將字符串params1轉換爲params2指定的數據類型。

3.3 示例代碼

3.3.1 單個對象的解析

public class Student {
    private int stu_no;
    private String stu_name;
    private String stu_sex;

    Student(int stu_no,String stu_name,String stu_sex){
        this.stu_no = stu_no;
        this.stu_name = stu_name;
        this.stu_sex = stu_sex;
    }
}

// 序列化,將Student對象stu轉換爲字符串str
Student stu = new Student(123,"Tom","male");
Gson gson = new Gson();
String str = gson.toJson(stu); 

//反序列化,將字符串轉換爲Student對象
jsonData = "{ \"stu_no\":12345,\"stu_name\":\"John\",\"stu_sex\":\"male\" }";
Gson gson = new Gson();
Student student = gson.fromJson(jsonData,Student.class);

3.3.2 JSON數組的解析(原生類)

Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};

//序列化(serialization)
//將整數數組轉換爲JSON數組
gson.toJson(ints);     // ==> [1,2,3,4,5]
//將字符串數組轉換爲JSON數組
gson.toJson(strings);  // ==> ["abc", "def", "ghi"]

// 反序列化(Deserialization)
// 將JSON數組轉換爲原生類數組
// ints二、string2與ints、strings相等
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); 
String[] strings2 = gson.fromJson("[\"abc\", \"def\", \"ghi\"]",String[].class);

3.3.3 JSON數組的解析(自定義類)

//對於相似於2.2中的jsonData,包含3個Student對象
//與原生類不一樣,須要藉助TypeToken得到指望解析成的數據類型
//下列代碼運行後,students包含三個Student對象
Gson gson = new Gson();
List<Student> students;
students = gson.fromJson(jsonData, new TypeToken<List<Student>>(){}.getType()); // ==>[stu0,stu1,stu2]

3.4 更多方法

  • GSON的簡便之處在於其能夠將字符串自動映射爲原生或自定義對象,從而不須要手動編寫代碼進行解析。
  • GSON的更多方法能夠閱讀GSON在github上的用法介紹,README.md -> user guide。
相關文章
相關標籤/搜索