Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert HashMap to json Array in android?

Tags:

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)); 
like image 361
Sandeep Avatar asked Mar 14 '13 06:03

Sandeep


People also ask

Can you send a HashMap as JSON?

The most traditional way of converting a hashmap to JSON object is by calling JSONObject() and then passing the hashmap.

How to convert Map to JSON Array in Java?

We can convert a Map to JSON object using the toJSONString() method(static) of org. json. simple. JSONValue.

Is JSON a HashMap?

JSON is a text based object that different from HashMap.

How to put JSON object in HashMap?

You can also have the following solution: JSONObject jsonObject = new JSONObject(); jsonObject. put("empt_id", 1017); jsonObject. put("emp_name", "karthik"); HashMap<String, JSONObject> jsonObjectStore = new HashMap<String, JSONObject>(); jsonObjectStore.


1 Answers

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()+"]"); 
like image 143
Pragnani Avatar answered Oct 23 '22 09:10

Pragnani