Modifying/Updating values inside a jsonArray?

17,027

Solution 1

As I understood, your problem is in creating multiple JSONObjects in your JSONArray with the same values, and that's because you can't get the index of a created JSONObject inside your JSONArray, and to overcome this problem, you can easily create a compound JSONObject that contains your JSONObjects instead of a JSONArray contains JSONObjects, and the object name will be anything unique in your JSONObject data, and when you make any changes or add any item it will either be added as a new object if it doesn't exist or it will overwrite the existing object if it added before, for example let's suppose that barcode value is unique in your data, so the code will be like the following:

// declaring itemSelectedJson as JSONObject 
JSONObject itemSelectedJson = new JSONObject();
.
.
.
// when wanting to add a new item
itemSelectedJson.put(jsonObject.getString("barcode"), jsonObject);

and to retrieve the data you simple iterate through this JSONObject:

Iterator<?> keys = itemSelectedJson.keys();
JSONObject single_item;
while(keys.hasNext()) {
    String key = (String)keys.next();
    single_item = itemSelectedJson.getJSONObject(key);
    // do what do you want here
}

Solution 2

A jSONObject(which is a collection of name,value pairs) can be converted into a JSONArray which is an ordered array of the "values" in the JSONObject.

This can be done using the .toJSONArray() method.

When you need to replace/update the JSONArray, you may use the method .put(int index, java.util.Map value)

Unlike how you are doing at present, i.e getting the object and setting a new key and value.

http://www.json.org/javadoc/org/json/JSONArray.html#put(int, java.util.Map)

Share:
17,027
AndroidNewBee
Author by

AndroidNewBee

Updated on June 04, 2022

Comments

  • AndroidNewBee
    AndroidNewBee almost 2 years

    What I want to do is at a particular index position change/replace a value inside a json array.After going through the documentation at http://www.json.org/javadoc/org/json/JSONArray.html I found out that jsonArray does not have a getIndex() method.In this situation how do I update my json array at a given index position. This is the method that creates a json array in my android code.

    private void createJsonArray() {
            billType = (invEstSwitch.isChecked() ? textViewEstimate : textViewInvoice)
                    .getText().toString();
            String invNumber = textViewInvNo.getText().toString();
            String bcode = barCode.getText().toString();
            String description = itemDesc.getText().toString();
            String wt = weightLine.getText().toString();
            String rateAmt = rateAmount.getText().toString();
            String making = makingAmount.getText().toString();
            String netr = netRate.getText().toString();
            String iTotal = itemtotal.getText().toString();
            String vatAmt = textViewVat.getText().toString();
            String sumAmt = textViewSum.getText().toString();
            String crtDate = textViewCurrentDate.getText().toString();
            try {
                jsonObject.put("custInfo", custSelected.toString());
                jsonObject.put("invoiceNo", invNumber);
                jsonObject.put("barcode", bcode);
                jsonObject.put("description", description);
                jsonObject.put("weight", wt);
                jsonObject.put("rate", rateAmt);
                jsonObject.put("makingAmt", making);
                jsonObject.put("net_rate", netr);
                jsonObject.put("itemTotal", iTotal);
                jsonObject.put("vat", vatAmt);
                jsonObject.put("sum_total", sumAmt);
                jsonObject.put("bill_type", billType);
                jsonObject.put("date", crtDate);
    
    
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                itemSelectedJson.put(index, jsonObject);
                index++;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    

    And this is the code that I use to update my json array which contains a json object.

      try {
                    itemSelectedJson.getJSONObject(i).put("net_rate",netChange);
                    Log.d("NETRATE_TW",itemSelectedJson.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
    

    Now the problem with this code is it updates the jsonArray everytime a new item is added to the code.So the first object values are the same as the last object.

    Also note that I am using this code inside a text watcher.So the afterTextchanged() method looks like this.

      @Override
            public void afterTextChanged(Editable s) {
                String netChange = netRate.getText().toString();
                final int row_id = (int) newRow.getTag();
    
                if ((row_id<0) || (row_id> itemSelectedJson.length())){
                    return;
                }
    
                try {
                    itemSelectedJson.getJSONObject(row_id-1).put("net_rate",netChange);
                    Log.d("NETRATE_TW",itemSelectedJson.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
      }
        };
    

    This is the snapshot of what my database looks like.

    enter image description here