import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ApiMirror {
/**
* Mirrors data from an API response, allowing for manual overrides.
*
* @param apiResponseData The raw data received from the API. Can be any type
* that can be mapped to a Map<String, Object>.
* @param overrideValues A map of keys to values to override the API response.
* @return A map representing the mirrored data with overrides applied. Returns an empty map if apiResponseData is null.
*/
public static Map<String, Object> mirrorData(Object apiResponseData, Map<String, Object> overrideValues) {
if (apiResponseData == null) {
return new HashMap<>(); // Return empty map if apiResponseData is null.
}
Map<String, Object> mirroredData = mapToMap(apiResponseData);
// Apply overrides
if (overrideValues != null) {
mirroredData.putAll(overrideValues); // Merge override values into mirrored data
}
return mirroredData;
}
/**
* Helper function to convert various data types to a Map<String, Object>.
* Handles Lists, Maps, and primitive types.
* @param data The data to convert.
* @return A Map<String, Object> representing the data.
*/
private static Map<String, Object> mapToMap(Object data) {
Map<String, Object> map = new HashMap<>();
if (data instanceof Map) {
Map<String, Object> mapData = (Map<String, Object>) data;
map.putAll(mapData);
} else if (data instanceof List) {
List<?> list = (List<?>) data;
for (int i = 0; i < list.size(); i++) {
map.put("item_" + i, list.get(i)); // Create keys like "item_0", "item_1", etc.
}
} else {
map.put("value", data); // Store primitive types or other single values.
}
return map;
}
public static void main(String[] args) {
// Example usage
// Simulate API response data
Map<String, Object> apiResponse = new HashMap<>();
apiResponse.put("id", 123);
apiResponse.put("name", "Original Name");
apiResponse.put("description", "Original Description");
List<String> items = new ArrayList<>();
items.add("Item 1");
items.add("Item 2");
apiResponse.put("items", items);
// Override values
Map<String, Object> overrides = new HashMap<>();
overrides.put("name", "Overridden Name");
overrides.put("id", 456); //Demonstrates overriding a numeric field
overrides.put("items", new ArrayList<>(){{add("Overridden Item");}}); // Demonstrates overriding a list.
// Mirror data with overrides
Map<String, Object> mirroredData = mirrorData(apiResponse, overrides);
// Print the mirrored data
System.out.println(mirroredData);
}
}
Add your comment