Search⌘ K
AI Features

Solution: Inventory Price Updater

Explore how to process JSON inventory data in Java by mapping it to immutable Product Records. Learn to update prices by creating new objects and save changes back to JSON using Jackson's ObjectMapper. This lesson helps you understand handling file I/O, JSON parsing, and working with immutable data structures in Java.

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();
}
}
}
...