Tuna Tuna - 8 months ago 61
Java Question

Java loop through JSON array and edit values

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.

... ]


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

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

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

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