Here's how to do the whole lot in 4 lines:
Map<String, String> map = new HashMap<String, String>();
String[] parts = json.replaceAll("^\\{|\\}$","").split("\"?(:|,)(?![^\\{]*\\})\"?");
for (int i = 0; i < parts.length -1; i+=2)
map.put(parts[i], parts[i+1]);
This works as follows:
- The head and tail braces are removed, because we can't easily split them out - they are junk
- The input is split by either a colon or a comma, optionally preceded/followed by a quote (this neatly consumes the quotes), but only if the next brace is not a close brace (meaning we're not in a nested term)
- Loop by 2's over the split result putting pairs of name/value into the map
Here's some test code:
public static void main(String[] args) throws Exception {
String json = "{name:\"X\",age:{dob:\"DD MMM\",year:YYYY}}";
Map<String, String> map = new HashMap<String, String>();
String[] parts = json.replaceAll("^\\{|\\}$","").split("\"?(:|,)(?![^\\{]*\\})\"?");
for (int i = 0; i < parts.length -1; i+=2)
map.put(parts[i], parts[i+1]);
System.out.println(map.size() + " entries: " + map);
}
Output:
2 entries: {age={dob:"DD MMM",year:YYYY}, name=X}