Jackson and JSON in Java, finally learn with a coding-first approach:
>> Download the eBookMocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely β and automatically β with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatβs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β one for newcomers and one for experienced users. Youβll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
1. Introduction
In this short tutorial, weβre going to learn how to use Jackson to read and write YAML files.
After we go over our example structure, weβll use the ObjectMapper to read a YAML file into a Java object and also write an object out to a file.
2. Dependencies
Letβs add the dependency for Jackson YAML data format:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.13.0</version>
</dependency>
We can always find the most recent version of this dependency on Maven Central.
Our Java object uses a LocalDate, so letβs also add a dependency for the JSR-310 datatype:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.13.0</version>
</dependency>
Again, we can look up its most recent version on Maven Central.
3. Data and Object Structure
With our dependencies squared away, weβll now turn to our input file and the Java classes weβll be using.
Letβs first look at the file weβll be reading in:
orderNo: A001
date: 2019-04-17
customerName: Customer, Joe
orderLines:
- item: No. 9 Sprockets
quantity: 12
unitPrice: 1.23
- item: Widget (10mm)
quantity: 4
unitPrice: 3.45
Then, letβs define the Order class:
public class Order {
private String orderNo;
private LocalDate date;
private String customerName;
private List<OrderLine> orderLines;
// Constructors, Getters, Setters and toString
}
Finally, letβs create our OrderLine class:
public class OrderLine {
private String item;
private int quantity;
private BigDecimal unitPrice;
// Constructors, Getters, Setters and toString
}
4. Reading YAML
Weβre going to use Jacksonβs ObjectMapper to read our YAML file into an Order object, so letβs set that up now:
mapper = new ObjectMapper(new YAMLFactory());
We need to use the findAndRegisterModules method so that Jackson will handle our Date properly:
mapper.findAndRegisterModules();
Once we have our ObjectMapper configured, we simply use readValue:
Order order = mapper.readValue(new File("src/main/resources/orderInput.yaml"), Order.class);
Weβll find that our Order object is populated from the file, including the list of OrderLine.
5. Writing YAML
Weβre also going to use ObjectMapper to write an Order out to a file. But first, letβs add some configuration to it:
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
Adding that line tells Jackson to just write our date as a String instead of individual numeric parts.
By default, our file will start with three dashes. Thatβs perfectly valid for the YAML format, but we can turn it off by disabling the feature on the YAMLFactory:
mapper = new ObjectMapper(new YAMLFactory().disable(Feature.WRITE_DOC_START_MARKER));
With that additional set up out of the way, letβs create an Order:
List<OrderLine> lines = new ArrayList<>();
lines.add(new OrderLine("Copper Wire (200ft)", 1,
new BigDecimal(50.67).setScale(2, RoundingMode.HALF_UP)));
lines.add(new OrderLine("Washers (1/4\")", 24,
new BigDecimal(.15).setScale(2, RoundingMode.HALF_UP)));
Order order = new Order(
"B-9910",
LocalDate.parse("2019-04-18", DateTimeFormatter.ISO_DATE),
"Customer, Jane",
lines);
Letβs write our order using writeValue:
mapper.writeValue(new File("src/main/resources/orderOutput.yaml"), order);
When we look into the orderOutput.yaml, it should look similar to:
orderNo: "B-9910"
date: "2019-04-18"
customerName: "Customer, Jane"
orderLines:
- item: "Copper Wire (200ft)"
quantity: 1
unitPrice: 50.67
- item: "Washers (1/4\")"
quantity: 24
unitPrice: 0.15
6. Conclusion
In this quick tutorial, we learned how to read and write YAML to and from files using the Jackson library. We also looked at a few configuration items that will help us get our data looking the way we want.
