Reputation: 13
I'm struggling to escape the double quotation marks when I try to convert my Map to String
//iterate through map and append to array
StringBuilder mapAsString = new StringBuilder("{");
for (String key : billingDetails.keySet()) {
mapAsString.append(key + ":" + billingDetails.get(key) + ", ");
}
mapAsString.delete(mapAsString.length()-2, mapAsString.length()).append("}");
String bdResult = mapAsString.toString();
Current output
"position": [
"{2018:Element3, 2012:Element2, 2010:Element1}"
Expected output
"position": [
"{"2018":"Element3", "2012":"Element2", "2010":"Element1"}"
Following method appends the contents of the Map to String however I can't seem to figure out how to escape the quotation marks so that the expected output is correct
mapAsString.append(key + ":" + billingDetails.get(key) + ", ");
Escaping characters in java has always been somewhat of a difficulty for me and I would appreciate it if someone with a wider knowledge would help me out
Cheers and thanks
Upvotes: 0
Views: 792
Reputation: 86
Escape the quotes with an backslash
mapAsString.append("\"" + key + "\":\"" + billingDetails.get(key) + "\", ");
Upvotes: 1