24

I want to convert HashMap to json array my code is as follow:

Map<String, String> map = new HashMap<String, String>();

map.put("first", "First Value");

map.put("second", "Second Value");

I have tried this but it didn't work. Any solution?

JSONArray mJSONArray = new JSONArray(Arrays.asList(map));
Rahul Khurana
  • 8,577
  • 7
  • 33
  • 60
Sandeep
  • 956
  • 2
  • 9
  • 19
  • 1
    So, you have a *Map*, but want an *Array*? Well, do that conversion first, *independent of JSON*, and then give the result (which is now a List/Array) to the appropriate JSON converter. The code posted won't work - and will result in a compiler error, which should be included in the post - because there is no `Arrays.asList(Map)`, as that doesn't make sense as there is no universal conversion (although, perhaps you want a List of the Entries?). That is, this question/problem has nothing to do with JSON directly. –  Mar 14 '13 at 06:09
  • @pst: thanks but there is any solution on it? to create array with key=> value and convert it to json? in android activity – Sandeep Mar 14 '13 at 06:12
  • Arrays *don't have* "key=>value". Provide sample Map data and the expected JSON Array output. –  Mar 14 '13 at 06:13
  • Key value is only available with Map family in collection,try to convert Map into String and play with String. – subodh Mar 14 '13 at 06:21

5 Answers5

49

Try this,

public JSONObject (Map copyFrom) 

Creates a new JSONObject by copying all name/value mappings from the given map.

Parameters copyFrom a map whose keys are of type String and whose values are of supported types.

Throws NullPointerException if any of the map's keys are null.

Basic usage:

JSONObject obj=new JSONObject(yourmap);

get the json array from the JSONObject

Edit:

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

Edit:(If found Exception then You can change as mention in comment by @krb686)

JSONArray array=new JSONArray("["+obj.toString()+"]");
rockstar
  • 587
  • 4
  • 22
Pragnani
  • 20,075
  • 6
  • 49
  • 74
  • I have tried but didn't work. Could you please paste code here? – Sandeep Mar 14 '13 at 06:29
  • I have no idea by what logic that is supposed to work. I can only hope it's tested - showing input and what it produces (at each stage) would make this an acceptable answer. –  Mar 14 '13 at 06:38
  • 1
    @Pragnani Unfortunately this doesn't work. Maybe it used to, but it doesn't anymore. This throws: `A JSONArray text must start with '[' at character 1` At the line creating the JSONArray from the JSONObject **Fix** You need to change to: `JSONArray array=new JSONArray("[" + obj.toString() + "]");` Could you edit that? Thanks – krb686 Jun 18 '14 at 18:50
  • In java 7, api 26 android, none of the solutions above produce a valid json array output. The map.toString() function produces braces, {}, not brackets, [] – Ed J Jun 25 '18 at 16:32
16

Since androiad API Lvl 19, you can simply do new JSONObject(new HashMap()). But on older API lvls you get ugly result(simple apply toString to each non-primitive value).

I collected methods from JSONObject and JSONArray for simplify and beautifully result. You can use my solution class:

package you.package.name;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;

public class JsonUtils
{
    public static JSONObject mapToJson(Map<?, ?> data)
    {
        JSONObject object = new JSONObject();

        for (Map.Entry<?, ?> entry : data.entrySet())
        {
            /*
             * Deviate from the original by checking that keys are non-null and
             * of the proper type. (We still defer validating the values).
             */
            String key = (String) entry.getKey();
            if (key == null)
            {
                throw new NullPointerException("key == null");
            }
            try
            {
                object.put(key, wrap(entry.getValue()));
            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
        }

        return object;
    }

    public static JSONArray collectionToJson(Collection data)
    {
        JSONArray jsonArray = new JSONArray();
        if (data != null)
        {
            for (Object aData : data)
            {
                jsonArray.put(wrap(aData));
            }
        }
        return jsonArray;
    }

    public static JSONArray arrayToJson(Object data) throws JSONException
    {
        if (!data.getClass().isArray())
        {
            throw new JSONException("Not a primitive data: " + data.getClass());
        }
        final int length = Array.getLength(data);
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < length; ++i)
        {
            jsonArray.put(wrap(Array.get(data, i)));
        }

        return jsonArray;
    }

    private static Object wrap(Object o)
    {
        if (o == null)
        {
            return null;
        }
        if (o instanceof JSONArray || o instanceof JSONObject)
        {
            return o;
        }
        try
        {
            if (o instanceof Collection)
            {
                return collectionToJson((Collection) o);
            }
            else if (o.getClass().isArray())
            {
                return arrayToJson(o);
            }
            if (o instanceof Map)
            {
                return mapToJson((Map) o);
            }
            if (o instanceof Boolean ||
                    o instanceof Byte ||
                    o instanceof Character ||
                    o instanceof Double ||
                    o instanceof Float ||
                    o instanceof Integer ||
                    o instanceof Long ||
                    o instanceof Short ||
                    o instanceof String)
            {
                return o;
            }
            if (o.getClass().getPackage().getName().startsWith("java."))
            {
                return o.toString();
            }
        }
        catch (Exception ignored)
        {
        }
        return null;
    }
}

Then if you apply mapToJson() method to your Map, you can get result like this:

{
  "int": 1,
  "Integer": 2,
  "String": "a",
  "int[]": [1,2,3],
  "Integer[]": [4, 5, 6],
  "String[]": ["a","b","c"],
  "Collection": [1,2,"a"],
  "Map": {
    "b": "B",
    "c": "C",
    "a": "A"
  }
}
senneco
  • 1,786
  • 2
  • 12
  • 15
  • 1
    Sweet! I wish I could give this +10! I'll have to look at the source code for API 19 to see if this is what they're doing. Thanks! – bstar55 Jun 20 '14 at 21:51
  • Had the same problem with undecodable string being sent looking like: {key=value, key2=value2} – Vans S Jul 06 '16 at 23:14
3

A map consists of key / value pairs, i.e. two objects for each entry, whereas a list only has a single object for each entry. What you can do is to extract all Map.Entry<K,V> and then put them in the array:

Set<Map.Entry<String, String> entries = map.entrySet();
JSONArray mJSONArray = new JSONArray(entries);

Alternatively, sometimes it is useful to extract the keys or the values to a collection:

Set<String> keys = map.keySet();
JSONArray mJSONArray = new JSONArray(keys);

or

List<String> values = map.values();
JSONArray mJSONArray = new JSONArray(values);

Note: If you choose to use the keys as entries, the order is not guaranteed (the keySet() method returns a Set). That is because the Map interface does not specify any order (unless the Map happens to be a SortedMap).

matsev
  • 32,104
  • 16
  • 121
  • 156
2

This is the Simplest Method.

Just use

JSONArray jarray = new JSONArray(hashmapobject.toString);
ImMathan
  • 3,911
  • 4
  • 29
  • 45
1

You can use

JSONArray jarray = JSONArray.fromObject(map );

Varun
  • 1,014
  • 8
  • 23
  • try this : http://stackoverflow.com/questions/9210273/how-to-create-a-complex-json-using-hashmap-in-android – Asraful Mar 14 '13 at 06:11
  • These classes are available in **JSON-Lib** library. You can find this library here: http://json-lib.sourceforge.net/ – Sadeshkumar Periyasamy Mar 14 '13 at 06:15
  • @Forhad: Thanks, But my hash created dynamically in my code so its not suitable for me is any other option to create array with key=>value and convert in json in android activity? – Sandeep Mar 14 '13 at 06:16