概要
jYamlでオブジェクトのリストをデシリアライズについて
ここまで出来るとテストクラスのリストデータ、など様々な用途で使えます。
サンプルコード
自作クラスのリストデータに対するデシリアライズサンプル
Yamlデータファイル(yaml_object_list.yml)
--- !jyaml.YamlChildData name: child1 nameType: FULL_NAME age: 10 --- !jyaml.YamlChildData name: child2 nameType: FIRST_NAME age: 11 --- !jyaml.YamlChildData name: child3 nameType: FAMILY_NAME age: 12
独自作成クラス
package jyaml; public class YamlChildData { private String name; private NameTypeEnum nameType; private int age; // アクセサメソッドは略 }
独自作成クラスで利用しているEnum
package jyaml; public enum NameTypeEnum { FIRST_NAME("1"),FAMILY_NAME("2"),FULL_NAME("3"); private String type; private NameTypeEnum(final String type) { this.type = type; } public String toValue() { return this.type; } public NameTypeEnum fromValue(String value) throws Exception { if (value.equals("1")) { return FIRST_NAME; } else if (value.equals("2")) { return FAMILY_NAME; } else if (value.equals("3")) { return FULL_NAME; } else { throw new IllegalArgumentException(); } } }
package jyaml; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import org.ho.yaml.Yaml; public class YamlObjectListSample { private final static String CONF_PATH = File.separator + "conf"; public static void main(String[] args) { try { String dir = System.getProperty("user.dir"); InputStream fs = new FileInputStream(dir + CONF_PATH + File.separator + "yaml_object_list.yml"); int count = 1; for (YamlChildData child : Yaml.loadStreamOfType(fs, YamlChildData.class)) { System.out.println(count); System.out.println(child.getName()); System.out.println(child.getNameType()); System.out.println(child.getAge()); count++; } } catch (FileNotFoundException e) { e.printStackTrace(); } } }
出力
1 child1 FULL_NAME 10 2 child2 FIRST_NAME 11 3 child3 FAMILY_NAME 12