java / intermediate
Snippet
Validating and Iterating Indexed Array Payloads in Web Controllers
When processing structured batch payloads, Spring automatically deserializes incoming JSON arrays into Java arrays or collections within data carrier records. Using indexed loop control structures allows developers to inspect individual array elements while tracking the exact index position for localized validation feedback, ensuring that malformed array elements can be pinpointed before transactional processing begins.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public record ItemEntry(String skuCode, int quantity) {}public record BatchShipmentRequest(ItemEntry[] entries) {}@RestController@RequestMapping("/shipments")public class ShipmentController {@PostMapping("/process-batch")public ResponseEntity<String> processShipment(@RequestBody BatchShipmentRequest request) {ItemEntry[] items = request.entries();if (items == null || items.length == 0) {return ResponseEntity.badRequest().body("Batch array cannot be empty");}int totalQuantity = 0;for (int i = 0; i < items.length; i++) {ItemEntry item = items[i];if (item.quantity() <= 0) {return ResponseEntity.unprocessableEntity().body("Invalid quantity at index " + i);}totalQuantity += item.quantity();}return ResponseEntity.ok("Processed " + items.length + " entries with " + totalQuantity + " total items");}}
spring
Breakdown
1
public record BatchShipmentRequest(ItemEntry[] entries) {}
Defines an immutable request carrier holding an array of structured item entries.
2
ItemEntry[] items = request.entries();
Extracts the deserialized array payload from the incoming request body record.
3
for (int i = 0; i < items.length; i++)
Iterates through array indices to perform boundary checks and locate validation failures.