Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

How to Process YAML with Jackson

$
0
0

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.9.8</version>
</dependency>

We can always find the most recent version of this dependency at 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.9.8</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 like 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.

The full example code is over on GitHub.


Viewing all articles
Browse latest Browse all 4535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>