How to add data into a json array instead of a ArrayList?
17,239
Solution 1
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.
Solution 2
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();
Related videos on Youtube
Author by
Anoop M Maddasseri
@🌴♓🎐🎵🎋🅿️🅰👢〽️ 🌴🎗🌜♓🎵⚽👢⚽🌀🎐🎗💲 🅵🅾🅲🆄🆂 🅾🅽 🆃🅷🅴 🆁🅾🅰🅳, 🅽🅾🆃 🆃🅷🅴 🆆🅰🅻🅻.!! 𝘏𝘦𝘭𝘭𝘰, 𝘵𝘩𝘢𝘯𝘬 𝘺𝘰𝘶 𝘧𝘰𝘳 𝘵𝘢𝘬𝘪𝘯𝘨 𝘵𝘩𝘦 𝘵𝘪𝘮𝘦 𝘵𝘰 𝘷𝘪𝘴𝘪𝘵. 𝘐 𝘴𝘱𝘦𝘤𝘪𝘢𝘭𝘪𝘻𝘦 𝘪𝘯 𝘴𝘪𝘮𝘱𝘭𝘦, 𝘦𝘧𝘧𝘦𝘤𝘵𝘪𝘷𝘦, 𝘶𝘴𝘦𝘳-𝘤𝘦𝘯𝘵𝘳𝘪𝘤 𝘥𝘦𝘴𝘪𝘨𝘯 / 𝘱𝘳𝘰𝘨𝘳𝘢𝘮𝘮𝘪𝘯𝘨 𝘴𝘰𝘭𝘶𝘵𝘪𝘰𝘯𝘴. 𝘍𝘪𝘭𝘭 𝘺𝘰𝘶𝘳 𝘴𝘦𝘯𝘴𝘦𝘴 𝘸𝘪𝘵𝘩 𝘩𝘪𝘨𝘩𝘭𝘪𝘨𝘩𝘵𝘴 𝘰𝘧 𝘸𝘰𝘳𝘬, 𝘳𝘦𝘢𝘥 𝘵𝘩𝘦 𝘫𝘶𝘪𝘤𝘺 𝘣𝘪𝘵𝘴 𝘢𝘣𝘰𝘶𝘵 𝘮𝘦, 𝘰𝘳 𝘧𝘪𝘯𝘥 𝘰𝘶𝘵 𝘸𝘩𝘺 𝘺𝘰𝘶 𝘴𝘩𝘰𝘶𝘭𝘥 𝘩𝘪𝘳𝘦 𝘮𝘦. #LinkedIn
Updated on September 15, 2022Comments
-
Anoop M Maddasseri over 1 year
What I am trying to do is add a Map into an
ArrayList
and then into aJsonArray
. What I intend to do is directly add the maps into the json array.//Initialize the ArrayList,Map and Json array private ArrayList<Map<String, String>> itemData = new ArrayList<>(); private Map<String, String> itemselected = new HashMap<>(); JSONArray itemSelectedJson = new JSONArray(); private void selectedItems() { if(invEstSwitch.isChecked()) { billType = textViewEstimate.getText().toString(); }else{ billType = textViewInvoice.getText().toString(); } itemselected.put("custInfo",custSelected.toString()); itemselected.put("invoiceNo", textViewInvNo.getText().toString()); itemselected.put("barcode", barCode.getText().toString()); itemselected.put("desc", itemDesc.getText().toString()); itemselected.put("weight", weightLine.getText().toString()); itemselected.put("rate", rateAmount.getText().toString()); itemselected.put("makingAmt", makingAmount.getText().toString()); itemselected.put("net_rate", netRate.getText().toString()); itemselected.put("itemTotal", itemtotal.getText().toString()); itemselected.put("vat", textViewVat.getText().toString()); itemselected.put("sum_total", textViewSum.getText().toString()); itemselected.put("bill_type", billType); itemselected.put("date", textViewCurrentDate.getText().toString()); //Add the map to the Array itemData.add(index, itemselected); itemSelectedJson= new JSONArray(Arrays.asList(itemData)); index++; }