有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将JSON插入SQLite(GSON+Volley)

来自此主题:Insert Gson Data into Android Sqlite

从截击的反应开始:

        public void onResponse(String response) {
        OverallModel itemList;
        itemList = new Gson().fromJson(response,OverallModel[].class);
        helper.insertData(itemList);

这是我的整体模型:

public class OverallModel {
    public int id;
    public String beschreibung;
    public String datum;
    public String image_link;
    public String location;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getBeschreibung() {
        return beschreibung;
    }

    public void setBeschreibung(String beschreibung) {
        this.beschreibung = beschreibung;
    }

... other getters and setters here

使用这样的JSON:

[
  {
    "id": "1",
    "name": "Event One",
    "beschreibung": "Description here - Skip quot'e's'?",
    "date": "14.01.2017",
    "image_link": "http://google.com/icon.png"
    "location":"location goes here"
  },
  {
    "id": "2",
    "name": "Event Two",
    "beschreibung": "Description here - Skip quot'e's'?",
    "date": "16.01.2017",
    "image_link": "http://google.com/icon.png"
    "location":"location goes here"
  },
  .
  .
  .
]

现在,我需要一个助手方法将数据放入SQLite DB,没有GSON,我使用以下代码:

JSONArray events = response.getJSONArray("events");
for (int h = 0; h < events.length(); h++) {
String jr_date = c.getString("datum");
String jr_imgurl = c.getString("image_link");
.
.
String SQLiteDataBaseQuery
                                = "INSERT INTO overall_table (id,des,name,date,imgurl,fburl,fbid,entry,open,closed) VALUES('"+id+"', '"+jr_descr+"', '"+jr_name+"', '"+jr_date+"', '"+jr_imgurl+"', '"+jr_fburl+"', '"+jr_fbid+"', '8.0' , '22:00', '3:30');";
                        sqLiteDatabase.execSQL(SQLiteDataBaseQuery);

使用DB Helper类:

public void onCreate(SQLiteDatabase database) {
String CREATE_TABLE="CREATE TABLE IF NOT EXISTS " +TAB_NAME+" ("+table_id+" INTEGER PRIMARY KEY, "
+table_desc+" VARCHAR, "
+ table_name+ " VARCHAR, "
+ table_date+" VARCHAR, "
.
.
+ table_open+" VARCHAR,"
+ table_closed+" VARCHAR)";
database.execSQL(CREATE_TABLE);
}

如何为GSON创建正确的Helper类,将反序列化数据放入我的表/DB中


共 (1) 个答案

  1. # 1 楼答案

    使用RoomORM数据库

    您可以轻松高效地插入模型列表