什么是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插件
三. 將一段Json格式的字符串轉(zhuǎn)化為相對于的Java對象
生成的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。