import org.json.JSONArray;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class JsonNormalizer {
/**
* Normalizes a JSON array of objects for synchronous execution.
* Converts all objects to a consistent map structure.
* @param jsonArray The JSON array to normalize.
* @return A map where keys are consistent and values are extracted from the JSON objects.
* Returns an empty map if the input is null or not a valid array.
*/
public static Map<String, String> normalizeJsonArray(JSONArray jsonArray) {
Map<String, String> normalizedData = new HashMap<>();
if (jsonArray == null || jsonArray.isEmpty()) {
return normalizedData; // Return empty map for null or empty array
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject != null) {
// Extract data, handling potential null values gracefully
String key1 = jsonObject.getString("id"); // Consistent key
String key2 = jsonObject.getString("name"); // Consistent key
String key3 = jsonObject.getString("value"); // Consistent key
normalizedData.put(key1, key2 + "_" + key3); // Combine values, using consistent keys
}
}
return normalizedData;
}
/**
* Normalizes a single JSON object for synchronous execution.
* Converts the object to a consistent map structure.
* @param jsonObject The JSON object to normalize.
* @return A map where keys are consistent and values are extracted from the JSON object.
* Returns an empty map if the input is null or not a valid object.
*/
public static Map<String, String> normalizeJsonObject(JSONObject jsonObject) {
Map<String, String> normalizedData = new HashMap<>();
if (jsonObject == null) {
return normalizedData;
}
try {
String key1 = jsonObject.getString("id");
String key2 = jsonObject.getString("name");
String key3 = jsonObject.getString("value");
normalizedData.put(key1, key2 + "_" + key3);
} catch (Exception e) {
// Handle potential errors during JSON extraction
System.err.println("Error normalizing JSON object: " + e.getMessage());
return new HashMap<>(); //Return empty map on error
}
return normalizedData;
}
public static void main(String[] args) {
// Example Usage:
String jsonString = "[{\"id\": \"1\", \"name\": \"Item1\", \"value\": \"10\"}, {\"id\": \"2\", \"name\": \"Item2\", \"value\": \"20\"}]";
JSONArray jsonArray = new JSONArray(jsonString);
Map<String, String> normalizedArray = normalizeJsonArray(jsonArray);
System.out.println("Normalized Array: " + normalizedArray);
JSONObject jsonObject = new JSONObject("{\"id\": \"3\", \"name\": \"Item3\", \"value\": \"30\"}");
Map<String, String> normalizedObject = normalizeJsonObject(jsonObject);
System.out.println("Normalized Object: " + normalizedObject);
}
}
Add your comment