您的位置:首页 > 移动开发 > Objective-C

Android中将List<Map<String, Object>>类型数据与字符串的相互转化

2015-02-11 14:47 941 查看
把List<Map<String, Object>>类型的数据转换为字符串,存入数据库,从数据库取出字符串,转换为List<Map<String, Object>>类型数据:

1)把List<Map<String, Object>>转换为字符串

<pre name="code" class="java">List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>();

<span style="white-space:pre">				</span>// 添加测试数据:
<span style="white-space:pre">				</span>for (int i = 0; i < 5; i++) {
<span style="white-space:pre">					</span>HashMap<String, Object> listm = new HashMap<String, Object>();
<span style="white-space:pre">					</span>listm.put("key", i);
<span style="white-space:pre">					</span>ls.add(listm);
<span style="white-space:pre">				</span>}
<span style="white-space:pre">				</span>// 将 ls 转换为字符串
<span style="white-space:pre">				</span>List<String> cache = new ArrayList<String>();
<span style="white-space:pre">				</span>for (int i = 0; i < ls.size(); i++) {
<span style="white-space:pre">					</span>// 取出当前的Map,转化为JSONObject
<span style="white-space:pre">					</span>JSONObject obj = new JSONObject(ls.get(i));
<span style="white-space:pre">					</span>// 转化为字符串并添加进新的List中
<span style="white-space:pre">					</span>cache.add(obj.toString());
<span style="white-space:pre">				</span>}
<span style="white-space:pre">				</span>// 可存储的字符串数据
<span style="white-space:pre">				</span>String lastdata = cache.toString();




2)把上面的生成的字符串还原成List<Map<String, Object>>

List<Map<String, Object>> item_temp = new ArrayList<Map<String, Object>>();
JSONArray ls = new JSONArray(lastdata);
if (ls.length()>0) {
for (int i=0;i<ls.length();i++) {
JSONObject json = new JSONObject(ls.get(i).toString());
HashMap<String, Object> listm = new HashMap<String, Object>();
listm.put("key", json.get("key"));
item_temp.add(listm);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐