Daniel Wilson
Daniel Wilson

Reputation: 19834

Put a Java Map to JSON

I have a map of string objects and keys that I wish to put to a json file. I have read that the way to do it is by converting it to an array, and it only works with maps where both the object and key are strings. I can create a JSONObject from the map fine, but cannot put that to an array. Can someone tell me why this does not work?

private static final String JSON_USER_VOTES = "user_votes";
private Map<String, String> mCheckedPostsMap; //This is populated elsewhere


JSONObject obj=new JSONObject(mCheckedPostsMap);
JSONArray array=new JSONArray(obj.toString()); // <<< Error is on this line
json.put(JSON_USER_VOTES, array);

Here is the error:

org.json.JSONException: Value {"232":"true","294":"true"} of type org.json.JSONObject cannot be converted to JSONArray

Upvotes: 1

Views: 7028

Answers (1)

isaolmez
isaolmez

Reputation: 1115

If you want all of initial map entries enclosed in one JSON object, you can use:

JSONArray array = new JSONArray().put(obj);

This will produce something like [{"key1:"value1","key2":"value2"}]

If you want each of initial map entries as different JSON object, you 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 will produce something like [{"key1:"value1"}, {"key2":"value2"}]

Upvotes: 2

Related Questions