我有ArrayList<HashMap<String,String>>
我正在使用toString()
方法存储在数据库中。
以下是我用来将toString()
存储到数据库的代码(它可以工作):
HashMap<String, String> commentsHash = null;
ArrayList<HashMap<String, String>> test2 = new ArrayList<HashMap<String, String>>();
for (int i=0; i < test.size(); i++)
{
String timestamp = test.get(i).get("timestamp");
String last_name = test.get(i).get("last_name");
String first_name = test.get(i).get("first_name");
String comment = test.get(i).get("comment");
commentsHash = new HashMap<String, String>();
commentsHash.put("creation_timestamp", timestamp);
commentsHash.put("first_name", first_name);
commentsHash.put("last_name", last_name);
commentsHash.put("comment", comment);
test2.add(commentsHash);
}
dbHelper.addCommentsToMyLiPost(Integer.parseInt(sqlId), test2.toString());
以下是我想用来将字符串转换为HashMap<String, String>
的方法:
protected HashMap<String,String> convertToStringToHashMap(String text){
HashMap<String,String> data = new HashMap<String,String>();
Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");
String[] split = p.split(text);
for ( int i=1; i+2 <= split.length; i+=2 ){
data.put( split[i], split[i+1] );
}
return data;
}
我尝试在字符串上使用.split(“,”)将字符串拆分为2部分,但不返回2,而是返回8.
以下是toString()
方法打印的内容。它是HashMaps的ArrayList,我试图抓住ArrayList中的两个HashMaps。
[{comment=hello, last_name=u1, first_name=u1, creation_timestamp=1404938643772}, {comment=hello2, last_name=u2, first_name=u2, creation_timestamp=1404963221598}]
答案 0 :(得分:1)
该程序将从数据库条目
重新创建整个列表 Pattern firstPat = Pattern.compile("\\{.*?\\}");
Matcher firstMat = firstPat.matcher(text);
ArrayList<HashMap<String, String>> list = new ArrayList<>();
while(firstMat.find()){
HashMap<String, String> map = new HashMap<>();
String assignStrings = firstMat.group();
String [] assignGroups = assignStrings.substring(1,assignStrings.length()-1).split("\\s*\\,\\s*");
for(String assign:assignGroups){
String [] parts = assign.split("\\=");
map.put(parts[0], parts[1]);
}
list.add(map);
}
return list
答案 1 :(得分:1)
在convertToStringToHashMap中,当您将数据放入HashMap时,旧值将被替换,因为它们对每条记录都有相同的键,例如comment,last_name等。
public static Map<String, Map<String, String>> convertToStringToHashMap(String text)
{
Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");
String[] split = p.split(text);
Map<String, String> data = new HashMap<String, String>();
int gap = 8;
int key = 1;
for (int i = 1; i + 2 <= split.length; i += 2)
{
data.put(split[i], split[i+1]);
if((i + 1) % gap == 0)
{
map.put(String.valueOf(key++), data);
data = new HashMap<String, String>();
data.clear();
}
}
return map;
}
这将返回Map:
2={first_name=u2, last_name=u2, comment=hello2, creation_timestamp=1404963221598}
1={first_name=u1, last_name=u1, comment=hello, creation_timestamp=1404938643772}