Json解析的三種方式

解析JSON
  • 方式一:使用org.json包解析
/**
     * 通過org.json解析json
     * @param jsonStr json字符串
     * @throws JSONException  格式不對,轉換異常
     */
    public static Sentence parseJsonByOrgJson(String jsonStr) throws JSONException{
        // 使用該方法解析思路,遇到大括號用JsonObject,中括號用JsonArray
        // 第一個是大括號{}
        JSONObject jsonObj = new JSONObject(jsonStr);
        // 新建Sentence對象
        Sentence sentence = new Sentence();
        // 以下是無腦操作
        String caption = jsonObj.getString("caption");
        String content = jsonObj.getString("content");
        String dateline = jsonObj.getString("dateline");
        String fenxiang_img = jsonObj.getString("fenxiang_img");
        String love = jsonObj.getString("love");
        String note = jsonObj.getString("note");
        String picture = jsonObj.getString("picture");
        String picture2 = jsonObj.getString("picture2");
        String s_pv = jsonObj.getString("s_pv");
        String sp_pv = jsonObj.getString("sp_pv");
        String translation = jsonObj.getString("translation");
        String tts = jsonObj.getString("tts");
        sentence.caption = caption;
        sentence.content = content;
        sentence.dateline = dateline;
        sentence.fenxiang_img = fenxiang_img;
        sentence.love = love;
        sentence.note = note;
        sentence.picture = picture;
        sentence.picture2 = picture2;
        sentence.s_pv = s_pv;
        sentence.sp_pv = sp_pv;
        sentence.translation = translation;
        sentence.tts = tts;
        
        // 解析關鍵字tags,它是一個JsonArray,遇到[]
        JSONArray jsonArray = jsonObj.getJSONArray("tags");
        // 新建Tag集合
        List<Sentence.Tag> tags = new ArrayList<Sentence.Tag>();
        for(int i=0;i<jsonArray.length();i++){
            Sentence.Tag tag = new Sentence.Tag();
            // jsonArray裏的每一項都是JsonObject
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            tag.id = jsonObject.getInt("id");
            tag.name = jsonObject.getString("name");
            tags.add(tag);
        }
        sentence.tags = tags;
        
        return sentence;
    }

 使用這種方法解析JSON,看註釋,沒什麼好多的,總結一句話就是:遇到{}用JSONObject,遇到[]用JSONArray,這樣你就可以說你精通org.json解析JSON了。

  • 方式二:使用JsonReader解析JSON,JsonReader解析JSON有點類似PULL解析XML,主要的方法還是nextName()將遊標後移。
    /**
     * Call requires API level 11 (current min is 8): new
     * android.util.JsonReader 通過org.json解析json
     * 
     * @param jsonStr
     *            json字符串
     * @throws Exception
     */
    @SuppressLint("NewApi")
    public static Sentence parseJsonByJsonReader(String jsonStr)
            throws Exception {
        // 新建Sentence
        Sentence sentence = new Sentence();
        // 新建Tag集合
        List<Sentence.Tag> tags = new ArrayList<Sentence.Tag>();
        JsonReader reader = new JsonReader(new StringReader(jsonStr));
        // 遇到{,開始解析對象
        reader.beginObject();
        while (reader.hasNext()) {
            String name = reader.nextName();
            if ("caption".equals(name)) {
                sentence.caption = reader.nextString();
            }
            if ("content".equals(name)) {
                sentence.content = reader.nextString();
            }
            if ("dateline".equals(name)) {
                sentence.dateline = reader.nextString();
            }
            if ("fenxiang_img".equals(name)) {
                sentence.fenxiang_img = reader.nextString();
            }
            if ("love".equals(name)) {
                sentence.love = reader.nextString();
            }
            if ("note".equals(name)) {
                sentence.note = reader.nextString();
            }
            if ("picture".equals(name)) {
                sentence.picture = reader.nextString();
            }
            if ("picture2".equals(name)) {
                sentence.picture2 = reader.nextString();
            }
            if ("s_pv".equals(name)) {
                sentence.s_pv = reader.nextString();
            }
            if ("sid".equals(name)) {
                sentence.sid = reader.nextString();
            }
            if ("sp_pv".equals(name)) {
                sentence.sp_pv = reader.nextString();
            }
            if ("translation".equals(name)) {
                sentence.translation = reader.nextString();
            }
            if ("tts".equals(name)) {
                sentence.tts = reader.nextString();
            }
            if ("tags".equals(name)) {
                // 遇到[,開始解析數組
                reader.beginArray();
                while (reader.hasNext()) {
                    // 遇到{,開始解析對象
                    reader.beginObject();
                    Sentence.Tag tag = new Sentence.Tag();
                    if ("id".equals(reader.nextName())) {
                        tag.id = reader.nextInt();
                    }
                    if ("name".equals(reader.nextName())) {
                        tag.name = reader.nextString();
                    }
                    // 遇到},對象解析結束
                    reader.endObject();
                    tags.add(tag);
                }
                sentence.tags = tags;
                // 遇到],數組解析結束
                reader.endArray();
            }
        }
        // 遇到},對象解析結束
        reader.endObject();
        return sentence;
    }

JsonReader解析JSON:

  • 當開始解析對象時(遇到"{"就JsonReader.beginObject()),當這個對象解析結束了(遇到"}")就endObject()結束對象的解析。
  • 當開始解析數組時(遇到"["就JsonReader.beginArray()),當這個數組解析結束了(遇到"]")就endArray()結束數組的解析。
  • 注意nextXXX()都會是遊標後移,如果有數據忘了解析等等導致遊標錯位,將會導致數據類型錯亂,這個時候就會很容易發生:java.lang.IllegalStateException: Expected a X but was Y ...參數匹配異常。所以一定不要漏了數據和注意每一次移動遊標。

  • 方式三:使用GSON解析

   1、下載Gson包放到項目lib目錄下面,並添加到構建路徑中

這裏寫圖片描述

gson的jar包下載:gson-2.5.jar

   2、編寫JavaBean

package com.example.jsonparsedemo;

import java.util.List;

// 由於簡單起見,直接用public
public class Sentence {
    
    public String caption;
    public String content;
    public String dateline;
    public String fenxiang_img;
    public String love;
    public String note;
    public String picture;
    public String picture2;
    public String s_pv;
    public String sid;
    public String sp_pv;
    public String translation;
    public String tts;
    
    public List<Tag> tags;
    
    static class Tag{
        public int id;
        public String name;
        
        @Override
        public String toString() {
            return "id=" + id + "\n" +
                    "name=" + name + "\n" ;
        }
    }

    @Override
    public String toString() {
        return "caption=" + caption + "\n" +
                "content=" + content+ "\n" +
                "dateline=" + dateline+ "\n" +
                "fenxiang_img=" + fenxiang_img+ "\n" +
                "love=" + love + "\n" +
                "note=" + note + "\n" +
                "picture=" + picture + "\n" +
                "picture2=" + picture2 + "\n" +
                "s_pv=" + s_pv + "\n" +
                "sid=" + sid + "\n" +
                "sp_pv="+ sp_pv + "\n" +
                "translation=" + translation + "\n" + 
                "tts=" + tts + "\n" +
                "tags=" + tags + "\n";
    }
    
}

 JavaBean的編寫(重點):

  • 其中屬性名稱和json數據的鍵名必須相同
  • 內部類不必是static(親測)
  • 類屬性可以是其他權限修飾符,包括private,並且可以不用寫setter和getter(親測)

  3、新建gson對象解析json,

/**
     * 通過GSON解析json
     * @param jsonStr
     * @return
     */
    public static Sentence parseJsonByGson(String jsonStr){
        Gson gson = new Gson();
        Sentence sentence = gson.fromJson(jsonStr, Sentence.class);
        return sentence;
    }

 就三行代碼,沒什麼說的,到這裏三種解析json的方式都介紹完了,感覺每種方式都好簡單,想不精通JSON解析都難。

JsonParseUtils.java的完整代碼:

package com.example.jsonparsedemo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.util.JsonReader;

import com.google.gson.Gson;

@SuppressLint("NewApi")
public class JsonParseUtils {

    /**
     * 連接網絡請求數據,這裏使用HttpURLConnection
     */
    public static String getJsonData() {
        URL url = null;
        String jsonData = ""; // 請求服務器返回的json字符串數據
        InputStreamReader in = null; // 讀取的內容(輸入流)
        try {
            url = new URL("http://open.iciba.com/dsapi");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 這一步會連接網絡得到輸入流
            in = new InputStreamReader(conn.getInputStream());
            // 爲輸入創建BufferedReader
            BufferedReader br = new BufferedReader(in);
            String inputLine = null;
            while (((inputLine = br.readLine()) != null)) {
                jsonData += inputLine;
            }
            in.close(); // 關閉InputStreamReader
            // 斷開網絡連接
            conn.disconnect();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return jsonData;
    }

    /**
     * 通過org.json解析json
     * 
     * @param jsonStr
     *            json字符串
     * @throws JSONException
     *             格式不對,轉換異常
     */
    public static Sentence parseJsonByOrgJson(String jsonStr)
            throws JSONException {
        // 使用該方法解析思路,遇到大括號用JsonObject,中括號用JsonArray
        // 第一個是大括號
        JSONObject jsonObj = new JSONObject(jsonStr);
        // 新建Sentence對象
        Sentence sentence = new Sentence();
        // 以下是無腦操作
        String caption = jsonObj.getString("caption");
        String content = jsonObj.getString("content");
        String dateline = jsonObj.getString("dateline");
        String fenxiang_img = jsonObj.getString("fenxiang_img");
        String love = jsonObj.getString("love");
        String note = jsonObj.getString("note");
        String picture = jsonObj.getString("picture");
        String picture2 = jsonObj.getString("picture2");
        String s_pv = jsonObj.getString("s_pv");
        String sid = jsonObj.getString("sid");
        String sp_pv = jsonObj.getString("sp_pv");
        String translation = jsonObj.getString("translation");
        String tts = jsonObj.getString("tts");
        sentence.caption = caption;
        sentence.content = content;
        sentence.dateline = dateline;
        sentence.fenxiang_img = fenxiang_img;
        sentence.love = love;
        sentence.note = note;
        sentence.picture = picture;
        sentence.picture2 = picture2;
        sentence.s_pv = s_pv;
        sentence.sid = sid;
        sentence.sp_pv = sp_pv;
        sentence.translation = translation;
        sentence.tts = tts;

        // 解析關鍵字tags,它是一個JsonArray
        JSONArray jsonArray = jsonObj.getJSONArray("tags");
        // 新建Tag集合
        List<Sentence.Tag> tags = new ArrayList<Sentence.Tag>();
        for (int i = 0; i < jsonArray.length(); i++) {
            Sentence.Tag tag = new Sentence.Tag();
            // jsonArray裏的每一項都是JsonObject
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            tag.id = jsonObject.getInt("id");
            tag.name = jsonObject.getString("name");
            tags.add(tag);
        }
        sentence.tags = tags;

        return sentence;
    }

    /**
     * Call requires API level 11 (current min is 8): new
     * android.util.JsonReader 通過org.json解析json
     * 
     * @param jsonStr
     *            json字符串
     * @throws Exception
     */
    @SuppressLint("NewApi")
    public static Sentence parseJsonByJsonReader(String jsonStr)
            throws Exception {
        // 新建Sentence
        Sentence sentence = new Sentence();
        // 新建Tag集合
        List<Sentence.Tag> tags = new ArrayList<Sentence.Tag>();
        JsonReader reader = new JsonReader(new StringReader(jsonStr));
        // 遇到{,開始解析對象
        reader.beginObject();
        while (reader.hasNext()) {
            String name = reader.nextName();
            if ("caption".equals(name)) {
                sentence.caption = reader.nextString();
            }
            if ("content".equals(name)) {
                sentence.content = reader.nextString();
            }
            if ("dateline".equals(name)) {
                sentence.dateline = reader.nextString();
            }
            if ("fenxiang_img".equals(name)) {
                sentence.fenxiang_img = reader.nextString();
            }
            if ("love".equals(name)) {
                sentence.love = reader.nextString();
            }
            if ("note".equals(name)) {
                sentence.note = reader.nextString();
            }
            if ("picture".equals(name)) {
                sentence.picture = reader.nextString();
            }
            if ("picture2".equals(name)) {
                sentence.picture2 = reader.nextString();
            }
            if ("s_pv".equals(name)) {
                sentence.s_pv = reader.nextString();
            }
            if ("sid".equals(name)) {
                sentence.sid = reader.nextString();
            }
            if ("sp_pv".equals(name)) {
                sentence.sp_pv = reader.nextString();
            }
            if ("translation".equals(name)) {
                sentence.translation = reader.nextString();
            }
            if ("tts".equals(name)) {
                sentence.tts = reader.nextString();
            }
            if ("tags".equals(name)) {
                // 遇到[,開始解析數組
                reader.beginArray();
                while (reader.hasNext()) {
                    // 遇到{,開始解析對象
                    reader.beginObject();
                    Sentence.Tag tag = new Sentence.Tag();
                    if ("id".equals(reader.nextName())) {
                        tag.id = reader.nextInt();
                    }
                    if ("name".equals(reader.nextName())) {
                        tag.name = reader.nextString();
                    }
                    // 遇到},對象解析結束
                    reader.endObject();
                    tags.add(tag);
                }
                sentence.tags = tags;
                // 遇到],數組解析結束
                reader.endArray();
            }
        }
        // 遇到},對象解析結束
        reader.endObject();
        return sentence;
    }
    
    /**
     * 通過GSON解析json
     * @param jsonStr
     * @return
     */
    public static Sentence parseJsonByGson(String jsonStr){
        Gson gson = new Gson();
        Sentence sentence = gson.fromJson(jsonStr, Sentence.class);
        return sentence;
    }
}
發佈了46 篇原創文章 · 獲贊 3 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章