Android中gson、jsonobject解析JSON的方法詳解_Android

來源:互聯網
上載者:User

JSON的定義:

一種輕量級的資料交換格式,具有良好的可讀和便於快速編寫的特性。業內主流技術為其提供了完整的解決方案(有點類似於Regex ,獲得了當今大部分語言的支援),從而可以在不同平台間進行資料交換。JSON採用相容性很高的文字格式設定,同時也具備類似於C語言體系的行為。

JSON對象:

JSON中對象(Object)以"{"開始, 以"}"結束. 對象中的每一個item都是一個key-value對, 表現為"key:value"的形式, key-value對之間使用逗號分隔. 如:{"name":"coolxing", "age"=24, "male":true, "address":{"street":"huiLongGuan", "city":"beijing", "country":"china"}}. JSON對象的key只能是string類型的, 而value可以是string, number, false, true, null, Object對象甚至是array數組, 也就是說可以存在嵌套的情況.

JSON數組:

JSON數組(array)以"["開始, 以"]"結束, 數組中的每一個元素可以是string, number, false, true, null, Object對象甚至是array數組, 數組間的元素使用逗號分隔. 如["coolxing", 24, {"street":"huiLongGuan", "city":"beijing", "country":"china"}].

1.前言

JSON資料是android網路開發中常見的資料格式。解析JSON資料有多種方法。

1.1 使用官方內建JSONObject

1.2 使用第三方開源庫,包括但不限於 GSON 、 FastJSON 、 Jackson ,本文主要介紹由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"}]

3.GSON的使用方法

3.1 下載並安裝

•將下載的gson-2.6.1.jar複製到 項目目錄->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轉換為字串strStudent 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數群組轉換為原生類數組// ints2、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。

以上內容給大家介紹了Android中gson、jsonobject解析JSON的方法詳解,希望對大家有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.