1

i have a Json array,on each object i want to edit the values of a specific keys accordingly

For example how can i loop through this array and edit the "unix_time" key of each object.

[{"_id":"","__v":0,"read":false,"timestamp":"","unix_time":"1477924542020"},
{"_id":"","__v":0,"read":false,"timestamp":"","unix_time":"1477924542020"},
{"_id":"","__v":0,"read":false,"timestamp":"","unix_time":"1477924532440"}, 
...
...
... ]
Ceddy Muhoza
  • 636
  • 3
  • 17
  • 34

2 Answers2

1

Below is test class. Please let me know if this helps

package com.test;

import org.json.JSONArray;
import org.json.JSONObject;

public class JSONTest {
public static void main(String[] args){
JSONArray jsonArray = new JSONArray();
JSONObject j1 = new JSONObject();
j1.put("id", "1");
j1.put("read", "false");
j1.put("time", "143250176");
jsonArray.put(j1);

JSONObject j2 = new JSONObject();
j2.put("id", "2");
j2.put("read", "false");
j2.put("time", "143250177");
jsonArray.put(j2);

JSONObject j3 = new JSONObject();
j3.put("id", "3");
j3.put("read", "false");
j3.put("time", "143250178");
jsonArray.put(j3);

JSONArray newArray = new JSONArray();
for(int count=0; count<jsonArray.length(); count++)
{
    JSONObject localInstance = jsonArray.getJSONObject(count);
    if(localInstance.optString("time") != "")
    {
        String time = localInstance.getString("time");
        String newTime = "new "+time;
        localInstance.put("time", newTime);
        newArray.put(localInstance);
    }
}
System.out.println(newArray);
}
}
Sachin Goyal
  • 98
  • 2
  • 12
0

Try:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Test {

    public static void main(String[] args) throws JSONException {
        String data = "[{\"_id\":\"\",\"read\":false,\"timestamp\":\"\",\"unix_time\":1477924542020},"
                + "{\"_id\":\"\",\"read\":false,\"timestamp\":\"\",\"unix_time\":1477924542121},"
                + "{\"_id\":\"\",\"read\":false,\"timestamp\":\"\",\"unix_time\":1477924532440}]";

        JSONArray jArray = new JSONArray(data);
        System.out.println(jArray);

        JSONArray newJArray = new JSONArray(data);

        JSONObject jsonObj;
        for (int i = 0; i < jArray.length(); i++) {
            jsonObj = (JSONObject) jArray.get(i);

            jsonObj.put("new_unix_time", jsonObj.remove("unix_time"));

        }
        System.out.println(jArray);
    }
}
Young Emil
  • 2,220
  • 2
  • 26
  • 37