【Java】JacksonでYAMLファイルを読み込む(record使用)

概要

以前作成した記事では、publicなフィールドをもつクラスを使ってYAMLのデータを読み込みました。
今回はrecordを使用してYAMLのデータを読み込む方法を紹介します。

前回の記事: JavaでYAMLファイルを読み込む(Jackson)

使用するデータ(users.yaml)

users:
  - email: tanaka@example.com
    name: Tanaka-san
    age: 20
    message: こんにちは!
    address:
      country: Japan
      city: Tokyo
  - email: smith@example.com
    name: John Smith
    age: 32
    message: Hello!
    address:
      country: United States
      city: New York
  - email: ivan@example.com
    name: Ivan Petrovich
    age: 51
    message: Привет!
    address:
      country: Russia
      city: Saint-Petersburg

pom.xml (一部抜粋)

  • Java 21
  • Jackson 2.18.2
<properties>
    <maven.compiler.source>21</maven.compiler.source>
    <maven.compiler.target>21</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.18.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-yaml -->
    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-yaml</artifactId>
        <version>2.18.2</version>
    </dependency>
</dependencies>

コード

最も基本的な使い方であると思われる、YAMLのデータ構造に対応するrecordを用意してObjectMapperreadValue()メソッドで読み込む方法を紹介します。

package com.github.maeda6uiui.loadyamlsample;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

record Address(String country, String city) {
}

record User(
        String email,
        String name,
        int age,
        String message,
        Address address
) {
}

record Users(List<User> users) {
}

public class Main {
    public static void main(String[] args) {
        try {
            String yamlContent = Files.readString(Path.of("./users.yaml"));

            var mapper = new ObjectMapper(new YAMLFactory());
            Users users = mapper.readValue(yamlContent, Users.class);

            users.users().forEach(v -> {
                System.out.printf("%s (%s) lives in %s\n", v.name(), v.email(), v.address().city());
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

このコードを実行すると、以下のような文字列が出力されます。

Tanaka-san (tanaka@example.com) lives in Tokyo
John Smith (smith@example.com) lives in New York
Ivan Petrovich (ivan@example.com) lives in Saint-Petersburg

recordのフィールド名とYAMLのフィールド名が異なる場合は、アノテーションを付加してYAMLのフィールド名を指定します。
通常のクラスを用いる場合と同じです。

record User(
        String email,
        @JsonProperty("namae") String name,
        int age,
        String message,
        Address address
) {
}