gpt4 book ai didi

java - 如何将 sqlite 中的数组与 json 数组的内容进行比较

转载 作者:太空宇宙 更新时间:2023-11-04 14:52:59 28 4
gpt4 key购买 nike

您好,我在比较来自 sqlite 数据库的数组和来自 Web 服务响应的 json 数组的最佳策略时遇到了问题。请告诉我比较这两个数组的最佳方法。这是我的代码:

public void getAllElements() {
Map<String, String> map = new HashMap<String, String>();
try {
//select all query
db.open();
Cursor cc= db.getAllEntries();
try {
// looping through all rows and adding to list
if (cc.moveToFirst()) {
do {
map.put("ID",cc.getString(cc.getColumnIndex(DbHelper.ENTRY_ID)));
} while (cc.moveToNext());
}
} finally {
try { cc.close(); } catch (Exception ignore) {}
}
} finally {
try { db.close(); } catch (Exception ignore) {}
}
// return list
}

protected String doInBackground(String... params) {
// Creating service handler class instance

JSONParser jParser = new JSONParser();
DefaultHttpClient client = new DefaultHttpClient(); // Thread
String uri = "url";

HttpGet httpget = new HttpGet(uri);
httpget.setHeader("Cookie", cookie);

try {
response = client.execute(httpget);
// response
String res = EntityUtils.toString(response.getEntity());

// jarray with the json responde
jArr = new JSONArray(res);
System.out.println("response" + jArr);

for (int i = 0; i < jArr.length(); i++) {
// create json object
JSONObject jsonObject = jArr.getJSONObject(i);
// easy parse fields
String vid = jsonObject.getString("vid");
String nid = jsonObject.getString("nid");
// uid value
String field_text = jsonObject.getString("field_text");
String field_edit_ts = jsonObject.getString("field_editts");
String field_deleted_flag = jsonObject.getString("field_deleted");
String field_device_name = jsonObject.getString("field_devicename");
String field_creation_ts = jsonObject.getString("field_creationts");
String field_device_key = jsonObject.getString("field_devicekey");
}
} catch(Exception e){
}
}

最佳答案

我建议将数据库和 JSON 数据包装在 class 中,并实现 equals(Object) 方法。

对于您的 JSON 数据,一旦您有了一个类(如上所述),我将使用 GSON ( https://code.google.com/p/google-gson/ ) 直接转换为对象

然后,为了进行比较,将数据库或 JSON 数据转换为 List(来自 Collections 的内容,或 HashTable/HashMap(搜索速度更快))并使用Collections.contains(Object)(在List上)方法和一个包含计数,您可以将其与列表的大小。举例如下,填空:

List<YourObject> dbDataList = new ArrayList<YourObject>(Arrays.asList(yourDatabaseDataArray));
int containsCount = 0;
for (YourObject o : yourJsonDataArray){
if (dbDataList.contains(o))
containsCount ++;
}
// Success condition is up to you, I'm just comparing the sizes
if (containsCount == dbDataList.size()){
// Success!
} else {
// Failure
}

关于java - 如何将 sqlite 中的数组与 json 数组的内容进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23538265/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com