Android--Json數(shù)據(jù)解析

什么是jason

一種輕量級的數(shù)據(jù)交換格式,具有良好的可讀和便于快速編寫的特性。業(yè)內(nèi)主流技術(shù)為其提供了完整的解決方案(有點(diǎn)類似于正則表達(dá)式 ,獲得了當(dāng)今大部分語言的支持),從而可以在不同平臺間進(jìn)行數(shù)據(jù)交換。JSON采用兼容性很高的文本格式,同時也具備類似于C語言體系的行為。

jason格式規(guī)范

JSON數(shù)據(jù)在名稱/值對中;數(shù)據(jù)由逗號分隔;花括號保存對象;方括號保存數(shù)組;
Json數(shù)據(jù)的書寫格式:名稱/值對 比如: "person":"coder-pig" 。

Array里面可以包含對象(object):

[ {"id":"1","name":"基神","age":"18"},  //一個無序的名稱/值對集合即為一個對象
 {"id":"2","name":"B神","age":"18"},
 {"id":"3","name":"曹神","age":"18"}  ]
//這是一個對象數(shù)組

對象(object)中可以包含Array

{"root":[ {"id":"001","name":"小豬"},{"id":"002","name":"小貓"},
          {"id":"003","name":"小狗"} ],
 "total":3,
 "success":true
}

可以對象嵌套子對象,子對象再嵌套數(shù)組

{"calendar": 
    {"calendarlist": [ {"id":"001","name":"小豬"}, {"id":"002","name":"小貓"} ] } 
}
利用jason存儲音樂列表信息

新建一個音樂項(xiàng)類

public class MusicItem {
    //jason數(shù)據(jù)的名稱
    public static final String JSON_NAME = "name";
    public static final String JSON_PATH = "path";
    public static final String SINGER = "singer";
    public static final String LENGTH = "length";
    private String name, singer, path;
    private int mLength;

    public MusicItem (String name, String singer, String path, int length) {
        this.name = name;
        this.path = path;
        this.singer = singer;
        mLength = length;
    }

    public MusicItem (JSONObject json) throws JSONException {
        name = json.getString(JSON_NAME);
        path = json.getString(JSON_PATH);
        singer = json.getString(SINGER);
        mLength = json.getInt(LENGTH);
    }

    public String getName() { return name; }

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

    public String getSinger() { return singer; }

    public void setSinger(String singer) { this.singer = singer; }

    public String getPath() { return path; }

    public void setPath(String path) { this.path = path; }

    public JSONObject toJSON() throws JSONException {
        //轉(zhuǎn)換成jason數(shù)據(jù)
        JSONObject json = new JSONObject();
        json.put(JSON_NAME, name);
        json.put(JSON_PATH, path);
        json.put(SINGER, singer);
        json.put(LENGTH, mLength);
        return json;
    }
}

JSONObject是系統(tǒng)中有關(guān)JSON定義的基本單元,其包含一個鍵值對值。利用JSONObject的put方法可以添加鍵值對到一個jason對象。

新建一個音樂列表jason序列化類

public class MusicJSONSerializer {
    public static final String MUSIC_JSON_SERIALIZER = "musicJSONSerializer";
    private Context mContext;
    private String mFileName;

    public MusicJSONSerializer(String mFileName, Context mContext) {
        this.mFileName = mFileName;
        this.mContext = mContext;
    }

    public void saveMusic(ArrayList<MusicItem> musics) throws JSONException,IOException {
        JSONArray array = new JSONArray();  
        //獲取一個JSONArray對象
        for (MusicItem music : musics) {
            array.put(music.toJSON());  
            //將musicItem數(shù)據(jù)轉(zhuǎn)換成Jason數(shù)據(jù)然后添加到JSONArray中
        }

        Writer writer = null;
        try {  
            //保存Jason數(shù)據(jù)到文件中
            OutputStream out = mContext.openFileOutput(mFileName,Context.MODE_PRIVATE);
            //Open a private file associated with this Context's application package for writing. Creates the file if it doesn't already exist.
            writer = new OutputStreamWriter(out);
            writer.write(array.toString());
        }finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    public ArrayList<MusicItem> loadMusic() throws IOException,JSONException {
        ArrayList<MusicItem> musics = new ArrayList<MusicItem>();
        BufferedReader reader = null;
        try {
            //讀取文件中的jason數(shù)據(jù)
            InputStream in = mContext.openFileInput(mFileName);
            reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder jsonString = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                jsonString.append(line);
            }

            //通過JSONTokener的nextValue()來獲得JSONObject對象,
            //然后再通過JSONObject對象來做進(jìn)一步的解析。
            JSONArray array = (JSONArray)new JSONTokener(jsonString.toString()).nextValue();
            for (int i = 0; i < array.length(); i++) {
                musics.add(new MusicItem(array.getJSONObject(i)));
            }
        }catch (FileNotFoundException e) {
            Log.i(MUSIC_JSON_SERIALIZER,"未找到相關(guān)的Jason文件");
        }finally {
            if (reader != null) {
                reader.close();
            }
        }
        return musics;
    }
}

SONTokener是系統(tǒng)為JSONObject和JSONArray構(gòu)造器解析JSON source string的類,它可以從source string中提取數(shù)值信息。

JSONStringer這個類可以幫助快速和便捷的創(chuàng)建JSONtext。其最大的優(yōu)點(diǎn)在于可以減少由于格式的錯誤導(dǎo)致程序異常,引用這個類可以自動嚴(yán)格按照J(rèn)SON語法規(guī)則(syntaxrules)創(chuàng)建JSON text。每個JSONStringer實(shí)體只能對應(yīng)創(chuàng)建一個JSON text。

String myString = new JSONStringer().object().key("name")
                                    .value("小豬").endObject().toString();  
使用GSON解析JSON數(shù)據(jù)

Gson是一個Java庫,它不僅可以把Java對象轉(zhuǎn)化為Json格式,它也能將一段Json格式的字符串轉(zhuǎn)化為相對于的Java對象。Gson適用于所有Java對象,即使是那些你不知道源代碼的對象。

一. 添加gson庫
1.首先,在自己的android studio的項(xiàng)目中把gson庫添加進(jìn)來,右鍵 app 選擇open module settings



2.選擇app,然后點(diǎn)擊 Dependencies,在點(diǎn)擊3步中的Library dependency(依賴的庫)



3.在1所指的彈出的收索框中收索gson,然后點(diǎn)擊2 所指的收索,然后下面就會出現(xiàn)最新的gson庫,點(diǎn)擊OK

4.點(diǎn)擊上圖OK后,gson庫就出現(xiàn)在了dependency中了,這個時候還得點(diǎn)擊 2所指的OK(確認(rèn))按鈕。

二. 添加GsonFormat插件


添加GsonFormat插件

三. 將一段Json格式的字符串轉(zhuǎn)化為相對于的Java對象

利用Alt + s快捷鍵使用GsonFormat
可以修改Data Type(數(shù)據(jù)類型)和 Field name( 屬性名稱 )。

生成的Weather類

public class Weather {

    /**
     * type : forecast1d
     * weatherinfo : [{"city":"北京","cityid":"1","temp1":"22℃","temp2":"10℃","weather":"晴","ptime":"11:00"},
     * {"city":"上海","cityid":"2","temp1":"24℃","temp2":"12℃","weather":"晴","ptime":"11:00"}]
     */

    private String type;
    /**
     * city : 北京
     * cityid : 1
     * temp1 : 22℃
     * temp2 : 10℃
     * weather : 晴
     * ptime : 11:00
     */

    private List<WeatherinfoBean> weatherinfo;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public List<WeatherinfoBean> getWeatherinfo() {
        return weatherinfo;
    }

    public void setWeatherinfo(List<WeatherinfoBean> weatherinfo) {
        this.weatherinfo = weatherinfo;
    }

    public static class WeatherinfoBean {
        private String city;
        private String cityid;
        private String temp1;
        private String temp2;
        private String weather;
        private String ptime;

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getCityid() {
            return cityid;
        }

        public void setCityid(String cityid) {
            this.cityid = cityid;
        }

        public String getTemp1() {
            return temp1;
        }

        public void setTemp1(String temp1) {
            this.temp1 = temp1;
        }

        public String getTemp2() {
            return temp2;
        }

        public void setTemp2(String temp2) {
            this.temp2 = temp2;
        }

        public String getWeather() {
            return weather;
        }

        public void setWeather(String weather) {
            this.weather = weather;
        }

        public String getPtime() {
            return ptime;
        }

        public void setPtime(String ptime) {
            this.ptime = ptime;
        }
    }
}

然后利用fromJason( )方法將jasonString轉(zhuǎn)換成Weather對象

AssetManager am = getResources().getAssets();
InputStream is = am.open(testjason.txt);
BufferedReader bufReader = new BufferedReader(new InputStreamReader(is));
StringBuilder strBuilder = new StringBuilder();
String line = "";
while ( (line = bufReader.readline()) != null ) {
    strBuilder.append(line);
}
String jasonString = strBuilder.toString();
Gson gson = new Gson();
Weather weather = gson.fromJson(jasonString, Weather.class);

利用Gson的toJason方法可以將某個Weather對象裝換成jason string。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,663評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,125評論 3 414
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,506評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,614評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,402評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,934評論 1 321
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,021評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,168評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,690評論 1 333
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,596評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,784評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,288評論 5 357
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,027評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,404評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,662評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,398評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,743評論 2 370

推薦閱讀更多精彩內(nèi)容