把List>类型的数据转换为字符串,存入数据库,从数据库取出字符串,转换为List>类型数据:
1)把List>转换为字符串
List> ls = new ArrayList>();
// 添加测试数据:
for (int i = 0; i < 5; i++) {
HashMap listm = new HashMap();
listm.put("key", i);
ls.add(listm);
}
// 将 ls 转换为字符串
List cache = new ArrayList();
for (int i = 0; i < ls.size(); i++) {
// 取出当前的Map,转化为JSONObject
JSONObject obj = new JSONObject(ls.get(i));
// 转化为字符串并添加进新的List中
cache.add(obj.toString());
}
// 可存储的字符串数据
String lastdata = cache.toString();
2)把上面的生成的字符串还原成List>
List> item_temp = new ArrayList>();
JSONArray ls = new JSONArray(lastdata);
if (ls.length()>0) {
for (int i=0;i
JSONObject json = new JSONObject(ls.get(i).toString());
HashMap listm = new HashMap();
listm.put("key", json.get("key"));
item_temp.add(listm);
}
}