1

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 
7
  • 1
    You read wrong. Perhaps you should post a link to where you read that. Commented Mar 12, 2014 at 23:56
  • 1
    The error seems obvious: a String is not an array. What is obj? Commented Mar 12, 2014 at 23:57
  • Can you post the input map? Commented Mar 12, 2014 at 23:57
  • You can create a JSONObject from a Map using the constructor, as shown in the post - however, your actual problem and reported error seem wrong, and the use of obj.toString() is incorrect. Perhaps it should simply be: array = new JSONArray().put(obj);? Commented Mar 13, 2014 at 0:00
  • If you have a map you want to convert to JSON, find a JSON toolkit that accept maps and tell it to convert. A Map naturally converts to a JSON "object", only not all Java JSON toolkits know how to do the conversion (since some insist on operating only on their own custom classes). It makes about zero sense to convert the Map to an array. Commented Mar 13, 2014 at 0:01

1 Answer 1

2

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"}]

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.