1. import java.io.IOException;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. public class ApiPayloadImporter {
  5. public static void main(String[] args) {
  6. // Replace with your API endpoint
  7. String apiUrl = "https://example.com/api/data";
  8. try {
  9. // Fetch data from the API
  10. String response = fetchApiData(apiUrl);
  11. // Parse the JSON response
  12. Map<String, Object> data = parseJson(response);
  13. // Print the parsed data (for debugging)
  14. printData(data);
  15. } catch (IOException e) {
  16. System.err.println("Error fetching data: " + e.getMessage());
  17. } catch (Exception e) {
  18. System.err.println("Error processing data: " + e.getMessage());
  19. }
  20. }
  21. // Fetches data from the specified API endpoint
  22. private static String fetchApiData(String apiUrl) throws IOException {
  23. // Simulate API call (replace with actual HTTP client like HttpClient or OkHttp)
  24. // For demonstration, using a hardcoded response
  25. if (apiUrl.equals("https://example.com/api/data")) {
  26. return "{ \"name\": \"John Doe\", \"age\": 30, \"city\": \"New York\" }";
  27. } else {
  28. return "{ \"error\": \"API not found\" }";
  29. }
  30. }
  31. // Parses the JSON response into a Map
  32. private static Map<String, Object> parseJson(String json) {
  33. // Simple JSON parsing (replace with a proper JSON library like Jackson or Gson)
  34. Map<String, Object> data = new HashMap<>();
  35. if (json != null && !json.isEmpty()) {
  36. //Very basic parsing - assuming key:value pairs
  37. String[] pairs = json.split(",\\s*\\}");
  38. for(String pair : pairs) {
  39. String[] keyValue = pair.split(": ");
  40. if(keyValue.length == 2) {
  41. String key = keyValue[0].trim().replaceAll("\"","");
  42. String value = keyValue[1].trim().replaceAll("\"","");
  43. data.put(key, value);
  44. }
  45. }
  46. }
  47. return data;
  48. }
  49. // Prints the parsed data to the console
  50. private static void printData(Map<String, Object> data) {
  51. System.out.println("Parsed Data:");
  52. for (Map.Entry<String, Object> entry : data.entrySet()) {
  53. System.out.println(entry.getKey() + ": " + entry.getValue());
  54. }
  55. }
  56. }

Add your comment