1. import java.util.ArrayList;
  2. import java.util.HashMap;
  3. import java.util.List;
  4. import java.util.Map;
  5. public class ApiMirror {
  6. /**
  7. * Mirrors data from an API response, allowing for manual overrides.
  8. *
  9. * @param apiResponseData The raw data received from the API. Can be any type
  10. * that can be mapped to a Map<String, Object>.
  11. * @param overrideValues A map of keys to values to override the API response.
  12. * @return A map representing the mirrored data with overrides applied. Returns an empty map if apiResponseData is null.
  13. */
  14. public static Map<String, Object> mirrorData(Object apiResponseData, Map<String, Object> overrideValues) {
  15. if (apiResponseData == null) {
  16. return new HashMap<>(); // Return empty map if apiResponseData is null.
  17. }
  18. Map<String, Object> mirroredData = mapToMap(apiResponseData);
  19. // Apply overrides
  20. if (overrideValues != null) {
  21. mirroredData.putAll(overrideValues); // Merge override values into mirrored data
  22. }
  23. return mirroredData;
  24. }
  25. /**
  26. * Helper function to convert various data types to a Map<String, Object>.
  27. * Handles Lists, Maps, and primitive types.
  28. * @param data The data to convert.
  29. * @return A Map<String, Object> representing the data.
  30. */
  31. private static Map<String, Object> mapToMap(Object data) {
  32. Map<String, Object> map = new HashMap<>();
  33. if (data instanceof Map) {
  34. Map<String, Object> mapData = (Map<String, Object>) data;
  35. map.putAll(mapData);
  36. } else if (data instanceof List) {
  37. List<?> list = (List<?>) data;
  38. for (int i = 0; i < list.size(); i++) {
  39. map.put("item_" + i, list.get(i)); // Create keys like "item_0", "item_1", etc.
  40. }
  41. } else {
  42. map.put("value", data); // Store primitive types or other single values.
  43. }
  44. return map;
  45. }
  46. public static void main(String[] args) {
  47. // Example usage
  48. // Simulate API response data
  49. Map<String, Object> apiResponse = new HashMap<>();
  50. apiResponse.put("id", 123);
  51. apiResponse.put("name", "Original Name");
  52. apiResponse.put("description", "Original Description");
  53. List<String> items = new ArrayList<>();
  54. items.add("Item 1");
  55. items.add("Item 2");
  56. apiResponse.put("items", items);
  57. // Override values
  58. Map<String, Object> overrides = new HashMap<>();
  59. overrides.put("name", "Overridden Name");
  60. overrides.put("id", 456); //Demonstrates overriding a numeric field
  61. overrides.put("items", new ArrayList<>(){{add("Overridden Item");}}); // Demonstrates overriding a list.
  62. // Mirror data with overrides
  63. Map<String, Object> mirroredData = mirrorData(apiResponse, overrides);
  64. // Print the mirrored data
  65. System.out.println(mirroredData);
  66. }
  67. }

Add your comment