我正在解析JSON并尝试将JSON数据存储到SQLite数据库中,我的JSON中只有name
属性并且有大约15条记录,但我无法将所有记录存储到SQLite中 - 仍然仅将最后解析的记录存储到JSON中。
以下是我的JSON的样子:
{
"actors": [
{
"name": "Name 1"
},
{
"name": "Name 2"
},
{
"name": "Name 3"
},
.......
{
"name": "Name 15"
}
]
}
我如何将所有记录存储到JSON中?正如您在我的JSON中看到的,我有15条记录,但在SQLite中,我只获取最后一条JSON记录的数据(即 - 名称15)
@Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
actorsList.add(actor);
sqliteDB.open();
sqliteDB.deleteAll();
sqliteDB.insert(object.getString("name"));
sqliteDB.close();
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
答案 0 :(得分:3)
@Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
sqliteDB.open();
sqliteDB.deleteAll();
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
actorsList.add(actor);
sqliteDB.insert(object.getString("name"));
}
sqliteDB.close();
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
答案 1 :(得分:1)
在插入记录之前的for循环中,您正在删除数据库中的所有数据,这就是为什么只有您获得的最后一条记录,请尝试下面的代码
sqliteDB.open();
sqliteDB.deleteAll();
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
actorsList.add(actor);
sqliteDB.insert(object.getString("name"));
}
sqliteDB.close();