1. import org.json.JSONArray;
  2. import org.json.JSONObject;
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.List;
  6. import java.util.Map;
  7. public class JsonSplitter {
  8. /**
  9. * Splits a JSON array of objects based on optional flags.
  10. *
  11. * @param jsonArray The JSON array of objects to split.
  12. * @param flag1 Whether to split based on flag1.
  13. * @param flag2 Whether to split based on flag2.
  14. * @return A list of maps, where each map represents a split portion of the data.
  15. */
  16. public static List<Map<String, Object>> splitJson(JSONArray jsonArray, boolean flag1, boolean flag2) {
  17. List<Map<String, Object>> result = new ArrayList<>();
  18. Map<String, Object> currentMap = new HashMap<>();
  19. for (int i = 0; i < jsonArray.length(); i++) {
  20. JSONObject obj = jsonArray.getJSONObject(i);
  21. currentMap.putAll(obj); // Add all properties of the current object
  22. if (flag1 && obj.get("flag1") instanceof Boolean && (Boolean) obj.get("flag1")) {
  23. result.add(new HashMap<>(currentMap)); // Add a new map to the result
  24. currentMap.clear(); // Start a new map
  25. }
  26. if (flag2 && obj.get("flag2") instanceof Boolean && (Boolean) obj.get("flag2")) {
  27. result.add(new HashMap<>(currentMap)); // Add a new map to the result
  28. currentMap.clear(); // Start a new map
  29. }
  30. }
  31. // Add any remaining data in the current map
  32. if (!currentMap.isEmpty()) {
  33. result.add(new HashMap<>(currentMap));
  34. }
  35. return result;
  36. }
  37. public static void main(String[] args) {
  38. //Example Usage
  39. 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\"}]");
  40. List<Map<String, Object>> splitData = splitJson(jsonArray, true, true);
  41. for (Map<String, Object> map : splitData) {
  42. System.out.println(map);
  43. }
  44. }
  45. }

Add your comment