import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class JsonStreamer {
private final String jsonUrl;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public JsonStreamer(String jsonUrl) {
this.jsonUrl = jsonUrl;
}
public void startStreaming() {
scheduler.scheduleAtFixedRate(this::fetchAndPrintJson, 0, 10, TimeUnit.SECONDS); // Run every 10 seconds
}
private void fetchAndPrintJson() {
try (InputStream inputStream = java.net.URL.openConnection().getInputStream()) {
String jsonString = readJsonFromStream(inputStream);
if (jsonString != null) {
try {
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println(jsonObject.toString(2)); // Print with indentation
}
} catch (Exception e) {
System.err.println("Error parsing JSON: " + e.getMessage());
e.printStackTrace();
}
} else {
System.err.println("Failed to retrieve JSON data.");
}
} catch (IOException e) {
System.err.println("Error fetching JSON: " + e.getMessage());
e.printStackTrace();
}
}
private String readJsonFromStream(InputStream inputStream) throws IOException {
StringBuilder sb = new StringBuilder();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
sb.append(new String(buffer, 0, bytesRead));
}
return sb.toString();
}
public void stopStreaming() {
scheduler.shutdown();
}
public static void main(String[] args) throws IOException {
String jsonUrl = "https://jsonplaceholder.typicode.com/todos"; // Example JSON URL
JsonStreamer streamer = new JsonStreamer(jsonUrl);
streamer.startStreaming();
// Keep the main thread alive for a while to allow streaming
try {
Thread.sleep(60000); // Run for 60 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
streamer.stopStreaming();
}
}
Add your comment