tech.chakapoko.com
Home / Java / SnakeYAML

[Java]SnakeYAMLを使ってJavaオブジェクトをYAMLに変換する

SnakeYAMLを使ってJavaオブジェクトをYAMLに変換します。

変換するのは次のような User クラスです。

package com.example;

import java.util.Date;

public class User {

    private int id;

    private String name;

    private Date createdAt;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", createdAt=" + createdAt +
                '}';
    }

}

変換を行うコードは次の通りです。

package com.example;

import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.nodes.Tag;

import java.util.Date;

public class Example {

    public static void main(String[] args) {
        User user = new User();
        user.setId(1);
        user.setName("John Doe");
        user.setCreatedAt(new Date());
        Yaml yaml = new Yaml();

        System.out.println(yaml.dump(user));
        System.out.println(yaml.dumpAs(user, Tag.MAP, DumperOptions.FlowStyle.FLOW));
        System.out.println(yaml.dumpAs(user, Tag.MAP, DumperOptions.FlowStyle.BLOCK));
        System.out.println(yaml.dumpAsMap(user));
    }

}

結果は以下のようになります。

!!com.example.User {createdAt: !!timestamp '2019-05-30T23:59:24.748Z', id: 1, name: John
    Doe}

{createdAt: !!timestamp '2019-05-30T23:59:24.748Z', id: 1, name: John Doe}

createdAt: 2019-05-30T23:59:24.748Z
id: 1
name: John Doe

createdAt: 2019-05-30T23:59:24.748Z
id: 1
name: John Doe

SnakeYAMLの dump メソッド、 dumpAs メソッドは使い方によっては タグ情報 も出力します。

タグ情報を出したくなければ dumpAsMap メソッドを使います。