import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JsonSplitter {
/**
* Splits a JSON array of objects based on optional flags.
*
* @param jsonArray The JSON array of objects to split.
* @param flag1 Whether to split based on flag1.
* @param flag2 Whether to split based on flag2.
* @return A list of maps, where each map represents a split portion of the data.
*/
public static List<Map<String, Object>> splitJson(JSONArray jsonArray, boolean flag1, boolean flag2) {
List<Map<String, Object>> result = new ArrayList<>();
Map<String, Object> currentMap = new HashMap<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
currentMap.putAll(obj); // Add all properties of the current object
if (flag1 && obj.get("flag1") instanceof Boolean && (Boolean) obj.get("flag1")) {
result.add(new HashMap<>(currentMap)); // Add a new map to the result
currentMap.clear(); // Start a new map
}
if (flag2 && obj.get("flag2") instanceof Boolean && (Boolean) obj.get("flag2")) {
result.add(new HashMap<>(currentMap)); // Add a new map to the result
currentMap.clear(); // Start a new map
}
}
// Add any remaining data in the current map
if (!currentMap.isEmpty()) {
result.add(new HashMap<>(currentMap));
}
return result;
}
public static void main(String[] args) {
//Example Usage
JSONArray jsonArray = new JSONArray("[{\"id\": 1, \"flag1\": true, \"name\": \"Alice\"}, {\"id\": 2, \"flag1\": false, \"name\": \"Bob\"}, {\"id\": 3, \"flag2\": true, \"name\": \"Charlie\"}, {\"id\": 4, \"flag2\": false, \"name\": \"David\"}]");
List<Map<String, Object>> splitData = splitJson(jsonArray, true, true);
for (Map<String, Object> map : splitData) {
System.out.println(map);
}
}
}
Add your comment