Sandeep Sandeep - 8 months ago 41
Java Question

How to convert HashMap to json Array in android?

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

JSONArray mJSONArray = new JSONArray(Arrays.asList(map));


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


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()+"]");