How to add data into a json array instead of a ArrayList?
You can do this way:
JSONArray jRootArray = new JSONArray(); for (int i = 1; i <= 20; i++) { JSONObject jInnerObject = new JSONObject(); try { jInnerObject.put(String.valueOf(i), "Hello "+i); } catch (JSONException e) { e.printStackTrace(); } jRootArray.put(jInnerObject); } Log.i("JRootArray", jRootArray.toString());
Hope this will help you.
Try this:
private Map<String, String> itemselected = new HashMap<>(); private void selectedItems() { JSONArray itemSelectedJson = new JSONArray(); // Retrieve all keys Set<String> keys = itemselected.keySet(); // Add items to JSONArray as JSONObjects for(String key : keys) { itemSelectedJson.put( new JSONObject().put(key, itemselected.get(key)) ); }}
This way, you won't have to pass by an ArrayList
to fill your JSONArray
. Then, you can get your JSON string simply by calling the toString()
method on the JSON array:
String jsonString = itemSelectedJson.toString();