Search⌘ K
AI Features

Solution: Inventory Price Updater

Explore how to update inventory prices by reading JSON data into Java objects using Jackson's ObjectMapper. Understand handling immutable records and saving updated product arrays back to JSON files for effective data processing.

We'll cover the following...
Java 25
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public record Product(int id, String name, double price) {}
public static void updatePrices(String inputPath, String outputPath) throws IOException {
ObjectMapper mapper = new ObjectMapper();
File inputFile = new File(inputPath);
File outputFile = new File(outputPath);
// Read JSON directly into a Product array
Product[] products = mapper.readValue(inputFile, Product[].class);
// Iterate and update prices
for (int i = 0; i < products.length; i++) {
Product original = products[i];
// Calculate new price (increase by 10%)
double newPrice = original.price() * 1.10;
// Optional: Round to 2 decimal places
newPrice = Math.round(newPrice * 100.0) / 100.0;
// Create new record and replace in array
products[i] = new Product(original.id(), original.name(), newPrice);
}
// Write the updated array back to JSON
mapper.writeValue(outputFile, products);
}
public static void main(String[] args) {
try {
String inputFile = "products.json";
String outputFile = "updated-products.json";
// Run the update
updatePrices(inputFile, outputFile);
// Verify Output
Path resultPath = Path.of(outputFile);
if (Files.exists(resultPath)) {
System.out.println("Updated Inventory:");
System.out.println(Files.readString(resultPath));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
...