Put a Java Map to JSON -
i have map of string objects , keys wish put json file. have read way converting array, , works maps both object , key strings. can create jsonobject map fine, cannot put array. can tell me why not work?
private static final string json_user_votes = "user_votes"; private map<string, string> mcheckedpostsmap; //this populated elsewhere jsonobject obj=new jsonobject(mcheckedpostsmap); jsonarray array=new jsonarray(obj.tostring()); // <<< error on line json.put(json_user_votes, array); here error:
org.json.jsonexception: value {"232":"true","294":"true"} of type org.json.jsonobject cannot converted jsonarray
if want of initial map entries enclosed in 1 json object, can use:
jsonarray array = new jsonarray().put(obj);
this produce [{"key1:"value1","key2":"value2"}]
if want each of initial map entries different json object, can use:
jsonobject obj = new jsonobject(map); jsonarray array = new jsonarray(); for(iterator iter = obj.keys(); iter.hasnext(); ){ string key = (string)iter.next(); jsonobject o = new jsonobject().put(key, map.get(key)); array.put(o); }
this produce [{"key1:"value1"}, {"key2":"value2"}]
Comments
Post a Comment