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));
The most traditional way of converting a hashmap to JSON object is by calling JSONObject() and then passing the hashmap.
We can convert a Map to JSON object using the toJSONString() method(static) of org. json. simple. JSONValue.
JSON is a text based object that different from 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.
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()+"]");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With