I am converting a string to a HashMap<String, String>. Prior to using Regex on the string, I got rid of the outer brackets (HashMaps were part of an ArrayList), so only the braces were left.
This works fine on items that do not have any spaces, but as soon as I add a space to one of the values, it rearranges the order of the keys and values of the HashMap.
Is their a fix for this?
String test2 = comments.substring(1, comments.length()-1); // remove offending brackets so only braces left
String[] test = test2.split("(?<=\\}),"); // I want there to be a new array every time there is a },
for (String string : test){
HashMap<String, String> commHash = convertToStringToHashMap(string);
}
Here is the method I use to convert the final string to a HashMap:
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;
}
Here's what I want (simplified version):
{comments=Hello World, username=cmj}
Here is what I get:
{hello:comments world:cmj}
It completely ignores the spaces.
0 comments:
Post a Comment