Gson輕鬆解析json資料並儲存到Sqlite資料庫
阿新 • • 發佈:2019-02-12
今天給大家帶來的文章為通過Gson解析json資料並快速儲存至資料庫的文章。我們要儲存是json物件陣列,本文中的json陣列並非從後臺獲取,為了演示,直接手動構造。
需要儲存到資料庫的是手機的品牌和型號。所以,我們需要新建一個bean實體類去儲存我們的型號和品牌。在這,我先介紹2個工具,一個是Google官方的Gson解析jar包。
名為Gson.jar,這個百度下載就可以了。另外一個是序列化外掛Parcelable。在setting---->>>>plugin----->搜尋Parcelable。
。
好了,下面新建我們的bean,取名DeviceModelBean.java。新增屬性後,右鍵選擇Generate--->>>Parcelable,然後快速直接序列化。
package com.mero.wyt_register.bean; import android.os.Parcel; import android.os.Parcelable; /** * Created by chenlei on 2016/10/28. */ public class DeviceModelBean implements Parcelable { public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String model;//型號 public String brand;//品牌 @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.model); dest.writeString(this.brand); } protected DeviceModelBean(Parcel in) { this.model = in.readString(); this.brand = in.readString(); } public static final Parcelable.Creator<DeviceModelBean> CREATOR = new Parcelable.Creator<DeviceModelBean>() { @Override public DeviceModelBean createFromParcel(Parcel source) { return new DeviceModelBean(source); } @Override public DeviceModelBean[] newArray(int size) { return new DeviceModelBean[size]; } }; }
接下來,再看看我們的json字串的內容。這個字串是我按照預期目的而構造的。
json字串內容如下:
String jsonString = "[{\"brand\":\"華為\",\"model\":\"c8818\"},{\"brand\":\"華為\",\"model\":\"Y635\"}," + "{\"brand\":\"華為\",\"model\":\"Y635-CL00\"},{\"brand\":\"華為\",\"model\":\"P8 Lite\"},{\"brand\":\"華為\",\"model\":\"榮耀X2\"}," + "{\"brand\":\"華為\",\"model\":\"榮耀Hol-T00\"},{\"brand\":\"華為\",\"model\":\"榮耀3X暢玩版\"}," + "{\"brand\":\"華為\",\"model\":\"榮耀6\"},{\"brand\":\"華為\",\"model\":\"榮耀4C\"},{\"brand\":\"華為\",\"model\":\"榮耀X3升級版\"}," + "{\"brand\":\"華為\",\"model\":\"C8816\"},{\"brand\":\"華為\",\"model\":\"C8816D\"},{\"brand\":\"華為\",\"model\":\"Mate 7\"},{\"brand\":\"華為\",\"model\":\"榮耀暢玩4C\"}," + "{\"brand\":\"華為\",\"model\":\"榮耀7\"},{\"brand\":\"華為\",\"model\":\"榮耀暢玩4C\"},{\"brand\":\"華為\",\"model\":\"榮耀7\"},{\"brand\":\"華為\",\"model\":\"榮耀4A\"}," + "{\"brand\":\"華為\",\"model\":\"P8\"},{\"brand\":\"華為\",\"model\":\"C2900\"},{\"brand\":\"華為\",\"model\":\"Y320\"}," + "{\"brand\":\"華為\",\"model\":\"C8815\"},{\"brand\":\"華為\",\"model\":\"Mate\"},{\"brand\":\"華為\",\"model\":\"Y600\"}," + "{\"brand\":\"華為\",\"model\":\"榮耀6 Plus\"},{\"brand\":\"華為\",\"model\":\"C8817L\"},{\"brand\":\"華為\",\"model\":\"G5000\"}," + "{\"brand\":\"華為\",\"model\":\"C8817E\"},{\"brand:\":\"華為\",\"model\":\"榮耀6X\"},{\"brand\":\"華為\",\"model\":\"P8 Lite\"}," + "{\"brand\":\"華為\",\"model\":\"Ascend P8\"},{\"brand\":\"華為\",\"model\":\"榮耀暢玩4X\"},{\"brand\":\"華為\",\"model\":\"G629\"},{\"brand\":\"華為\",\"model\":\"G620\"},{\"brand\":\"華為\",\"model\":\"榮耀X2\"}," + "{\"brand\":\"華為\",\"model\":\"榮耀3C\"},{\"brand\":\"華為\",\"model\":\"榮耀6 Plus\"},{\"brand\":\"華為\",\"model\":\"C2800\"},{\"brand\":\"華為\",\"model\":\"2601\"},{\"brand\":\"華為\",\"model\":\"G610S\"}," + "{\"brand\":\"華為\",\"model\":\"Ascend G302D\"},{\"brand\":\"華為\",\"model\":\"Ascend G6\"},{\"brand\":\"華為\",\"model\":\"Ascend G6\"},{\"brand\":\"華為\",\"model\":\"T8950N\"}," + "{\"brand\":\"華為\",\"model\":\"G610\"},{\"brand\":\"華為\",\"model\":\"C8813DQ\"},{\"brand\":\"華為\",\"model\":\"Y618\"},{\"brand\":\"華為\",\"model\":\"G630\"}," + "{\"brand\":\"華為\",\"model\":\"G521\"},{\"brand\":\"華為\",\"model\":\"榮耀暢玩4\"}]";
仔細一看,其實就是一些物件陣列,每個物件裡面有2個元素,一個品牌,一個型號。
接下來,咱們就需要把這些屬性全部設定到物件數組裡去。
java.lang.reflect.Type type = new TypeToken<List<DeviceModelBean>>(){}.getType();
Gson gson = new Gson();
listDeviceModel = gson.fromJson(jsonString,type);
上面三行就可以將我們的json陣列設定到List<DeviceModelBean>數組裡去。在這裡說明一下上面的用法,Gson可以通過toJson和fromJson方法分別把物件拆分成json陣列和把json陣列設定到物件集合中。Type是個介面,位於java.lang.reflect包下。formJson通過傳入json字串陣列和type的介面物件從而設定到物件中去。
接下來,我們應該編寫資料庫幫助類和dao來完成資料庫的操作。首先,我們先建立一個數據庫幫助類DbHelper.java。
public class DbHelper extends SQLiteOpenHelper {
private Context context;
private static final String dbName = "bbzs.db";
public DbHelper(Context context){
super(context,dbName,null,1);
this.context = context;
}
//建立表
@Override
public void onCreate(SQLiteDatabase db) {
String sql1 = "create table if not exists device_model_info(id integer primary key AUTOINCREMENT,model varchar(20),brand varchar(20))";
db.execSQL(sql1);
}
//刪除資料庫
public void deleteDb(){
context.deleteDatabase(dbName);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
我們可以通過建立DbHelper物件來建立一個數據庫的例項和建立表。
然後我們可以寫我們的Dao。
dao的完整程式碼如下:
public class DeviceModelDao {
public static final String TAG = "DeviceModelDao";
Context context;
SQLiteDatabase db;
List<DeviceModelBean> listDeviceModel = null;
public DeviceModelDao(Context context){
this.context = context;
}
//Gson解析陣列到物件中去
public List<DeviceModelBean> addObjectToList(){
String jsonString = "[{\"brand\":\"華為\",\"model\":\"c8818\"},{\"brand\":\"華為\",\"model\":\"Y635\"}," +
"{\"brand\":\"華為\",\"model\":\"Y635-CL00\"},{\"brand\":\"華為\",\"model\":\"P8 Lite\"},{\"brand\":\"華為\",\"model\":\"榮耀X2\"}," +
"{\"brand\":\"華為\",\"model\":\"榮耀Hol-T00\"},{\"brand\":\"華為\",\"model\":\"榮耀3X暢玩版\"}," +
"{\"brand\":\"華為\",\"model\":\"榮耀6\"},{\"brand\":\"華為\",\"model\":\"榮耀4C\"},{\"brand\":\"華為\",\"model\":\"榮耀X3升級版\"}," +
"{\"brand\":\"華為\",\"model\":\"C8816\"},{\"brand\":\"華為\",\"model\":\"C8816D\"},{\"brand\":\"華為\",\"model\":\"Mate 7\"},{\"brand\":\"華為\",\"model\":\"榮耀暢玩4C\"}," +
"{\"brand\":\"華為\",\"model\":\"榮耀7\"},{\"brand\":\"華為\",\"model\":\"榮耀暢玩4C\"},{\"brand\":\"華為\",\"model\":\"榮耀7\"},{\"brand\":\"華為\",\"model\":\"榮耀4A\"}," +
"{\"brand\":\"華為\",\"model\":\"P8\"},{\"brand\":\"華為\",\"model\":\"C2900\"},{\"brand\":\"華為\",\"model\":\"Y320\"}," +
"{\"brand\":\"華為\",\"model\":\"C8815\"},{\"brand\":\"華為\",\"model\":\"Mate\"},{\"brand\":\"華為\",\"model\":\"Y600\"}," +
"{\"brand\":\"華為\",\"model\":\"榮耀6 Plus\"},{\"brand\":\"華為\",\"model\":\"C8817L\"},{\"brand\":\"華為\",\"model\":\"G5000\"}," +
"{\"brand\":\"華為\",\"model\":\"C8817E\"},{\"brand:\":\"華為\",\"model\":\"榮耀6X\"},{\"brand\":\"華為\",\"model\":\"P8 Lite\"}," +
"{\"brand\":\"華為\",\"model\":\"Ascend P8\"},{\"brand\":\"華為\",\"model\":\"榮耀暢玩4X\"},{\"brand\":\"華為\",\"model\":\"G629\"},{\"brand\":\"華為\",\"model\":\"G620\"},{\"brand\":\"華為\",\"model\":\"榮耀X2\"}," +
"{\"brand\":\"華為\",\"model\":\"榮耀3C\"},{\"brand\":\"華為\",\"model\":\"榮耀6 Plus\"},{\"brand\":\"華為\",\"model\":\"C2800\"},{\"brand\":\"華為\",\"model\":\"2601\"},{\"brand\":\"華為\",\"model\":\"G610S\"}," +
"{\"brand\":\"華為\",\"model\":\"Ascend G302D\"},{\"brand\":\"華為\",\"model\":\"Ascend G6\"},{\"brand\":\"華為\",\"model\":\"Ascend G6\"},{\"brand\":\"華為\",\"model\":\"T8950N\"}," +
"{\"brand\":\"華為\",\"model\":\"G610\"},{\"brand\":\"華為\",\"model\":\"C8813DQ\"},{\"brand\":\"華為\",\"model\":\"Y618\"},{\"brand\":\"華為\",\"model\":\"G630\"}," +
"{\"brand\":\"華為\",\"model\":\"G521\"},{\"brand\":\"華為\",\"model\":\"榮耀暢玩4\"}]";
try{
java.lang.reflect.Type type = new TypeToken<List<DeviceModelBean>>(){}.getType();
Gson gson = new Gson();
listDeviceModel = gson.fromJson(jsonString,type);
Log.e("TAG",type+"");
for(Iterator iterator = listDeviceModel.iterator();iterator.hasNext();){
DeviceModelBean bean = (DeviceModelBean) iterator.next();
Log.e(TAG,bean.getModel()+bean.getBrand());
}
}catch (Exception e){
Log.e(TAG,"錯誤:"+e.getMessage());
}
return listDeviceModel;
}
//插入資料到資料庫
public void insertModelToDb(List<DeviceModelBean> listDeviceModel){
try{
DbHelper dbHelper = new DbHelper(context);
db = dbHelper.getWritableDatabase();
//開始事務
db.beginTransaction();
Log.e(TAG,listDeviceModel.size()+"");
String sql1 = "insert into device_model_info(id,model,brand) values (?,?,?)";
for(DeviceModelBean f :listDeviceModel){
db.execSQL(sql1,new Object[]{null,f.model,f.brand});
}
}catch (Exception e){
e.printStackTrace();
}finally {
//提交
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
}
建立資料庫的指令碼為:
create table if not exists device_model_info(id integer primary key AUTOINCREMENT,model varchar(20),brand varchar(20))
執行插入的指令碼為:
insert into device_model_info(id,model,brand) values (?,?,?)
這裡注意的是第一個為主鍵id,這個必須得加上integer primary key 才會自動生成。另外,主鍵必須為null才可以,否則一直
在程式碼中的用法為:
//建立資料庫和表
DbHelper dbHelper = new DbHelper(MyApplication.getMyApplication());
//插入資料到資料庫
DeviceModelDao dao = new DeviceModelDao(MyApplication.getMyApplication());
dao.insertModelToDb(dao.addObjectToList());