如何将数据添加到json数组而不是ArrayList中



我要做的是将Map添加到ArrayList中,然后添加到JsonArray中。我打算做的是直接将映射添加到json数组中。

//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++;
}

您可以这样做:

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());

希望这对你有帮助。

试试这个:

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))
        );
    }
}

这样,您就不必经过一个ArrayList来填充您的JSONArray。然后,只需调用JSON数组上的toString()方法即可获得JSON字符串

String jsonString = itemSelectedJson.toString();

最新更新