string - toString() changes ":" to "=" in a java hashmap -
i have following
public static void main(string []args) throws jsonexception{ map<string,string> varmap = new hashmap<string,string>(); varmap.put("var","123"); varmap.put("other_var","234"); jsonobject json = new jsonobject(); json.put("variable",varmap); system.out.println("json " + json); }
this gives me correct result follows
json {"variable":{"var":"123","other_var":"234"}}
but in json can use string value, changing following gives me unexpected result
public static void main(string []args) throws jsonexception{ map<string,string> varmap = new hashmap<string,string>(); varmap.put("var","123"); varmap.put("other_var","234"); jsonobject json = new jsonobject(); json.put("variable",varmap.tostring()); system.out.println("json " + json); }
unexpected result
json {"variable":"{var=123, other_var=234}"}
i can achive manually replacing equal ":"
public class json{ public static void main(string []args) throws jsonexception{ map<string,string> varmap = new hashmap<string,string>(); varmap.put("var","123"); varmap.put("other_var","234"); jsonobject json = new jsonobject(); string jsonvarmap = varmap.tostring().replace("=", ":"); json.put("variable", jsonvarmap); system.out.println("json " + json); } }
but there better way? how change map exact string?
this because use hashmap::tostring()
:
json.put("variable",varmap.tostring());
and usual behaviour.
replace not bad in simple cases, if of data contents =
break json.
if want correct result in more polite mode, extend
hashmap
, override tostring
:
jsonmap.java
public class jsonmap<k,v> extends hashmap<k,v> { private static final long serialversionuid = 1l; private static string separator = ""; private static final char quote = '"'; private static final char dots = ':'; @override public string tostring() { stringbuilder sb = new stringbuilder(); (map.entry<k, v> entry : this.entryset()) { sb.append(separator); // same sb.append("" + quote + entry.getkey() + quote + ":" + quote + entry.getvalue() + quote); sb.append(quote); sb.append(entry.getkey()); sb.append(quote); sb.append(dots); sb.append(quote); sb.append(entry.getvalue()); sb.append(quote); separator = ", "; } return sb.tostring(); } }
execute it:
map<string,string> varmap = new jsonmap<string,string>(); varmap.put("var","123"); varmap.put("other_var","234"); system.out.println(varmap);
output:
"var":"123", "other_var":"234"
now, apply json expected result ;)
Comments
Post a Comment