1. import org.json.JSONArray;
  2. import org.json.JSONObject;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.util.concurrent.Executors;
  6. import java.util.concurrent.ScheduledExecutorService;
  7. import java.util.concurrent.TimeUnit;
  8. public class JsonStreamer {
  9. private final String jsonUrl;
  10. private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
  11. public JsonStreamer(String jsonUrl) {
  12. this.jsonUrl = jsonUrl;
  13. }
  14. public void startStreaming() {
  15. scheduler.scheduleAtFixedRate(this::fetchAndPrintJson, 0, 10, TimeUnit.SECONDS); // Run every 10 seconds
  16. }
  17. private void fetchAndPrintJson() {
  18. try (InputStream inputStream = java.net.URL.openConnection().getInputStream()) {
  19. String jsonString = readJsonFromStream(inputStream);
  20. if (jsonString != null) {
  21. try {
  22. JSONArray jsonArray = new JSONArray(jsonString);
  23. for (int i = 0; i < jsonArray.length(); i++) {
  24. JSONObject jsonObject = jsonArray.getJSONObject(i);
  25. System.out.println(jsonObject.toString(2)); // Print with indentation
  26. }
  27. } catch (Exception e) {
  28. System.err.println("Error parsing JSON: " + e.getMessage());
  29. e.printStackTrace();
  30. }
  31. } else {
  32. System.err.println("Failed to retrieve JSON data.");
  33. }
  34. } catch (IOException e) {
  35. System.err.println("Error fetching JSON: " + e.getMessage());
  36. e.printStackTrace();
  37. }
  38. }
  39. private String readJsonFromStream(InputStream inputStream) throws IOException {
  40. StringBuilder sb = new StringBuilder();
  41. int bufferSize = 1024;
  42. byte[] buffer = new byte[bufferSize];
  43. int bytesRead;
  44. while ((bytesRead = inputStream.read(buffer)) != -1) {
  45. sb.append(new String(buffer, 0, bytesRead));
  46. }
  47. return sb.toString();
  48. }
  49. public void stopStreaming() {
  50. scheduler.shutdown();
  51. }
  52. public static void main(String[] args) throws IOException {
  53. String jsonUrl = "https://jsonplaceholder.typicode.com/todos"; // Example JSON URL
  54. JsonStreamer streamer = new JsonStreamer(jsonUrl);
  55. streamer.startStreaming();
  56. // Keep the main thread alive for a while to allow streaming
  57. try {
  58. Thread.sleep(60000); // Run for 60 seconds
  59. } catch (InterruptedException e) {
  60. e.printStackTrace();
  61. }
  62. streamer.stopStreaming();
  63. }
  64. }

Add your comment