yaml key1: value1 key2: value2 list: - item1 - item2 Yaml yaml = new Yaml(); InputStream inputStream = new FileInputStream("example.yaml"); Map<String, Object> data = yaml.load(inputStream); yaml name: John Doe age: 30 public class Person { private String name; private int age; // getters and setters } Yaml yaml = new Yaml(); InputStream inputStream = new FileInputStream("person.yaml"); Person person = yaml.loadAs(inputStream, Person.class); public class CustomRepresenter extends Representer { public CustomRepresenter() { representers.put(CustomType.class, new RepresentCustomType()); } private class RepresentCustomType extends Represent { public Node representData(Object data) { } } } Yaml yaml = new Yaml(new CustomRepresenter()); CustomType customType = new CustomType(); String output = yaml.dump(customType); Person person = new Person("John Doe", 30); Yaml yaml = new Yaml(); String output = yaml.dump(person); String yamlString = "name: John Doe age: 30"; Yaml yaml = new Yaml(); Person person = yaml.loadAs(yamlString, Person.class); public class CustomType { private String value; public CustomType(String value) { this.value = value; } // getter and setter } public class CustomTypeConstructor extends Constructor { public CustomTypeConstructor() { yamlConstructors.put(Tag.STR, new ConstructCustomType()); } private class ConstructCustomType extends AbstractConstruct { public Object construct(Node node) { String value = (String) constructScalar((ScalarNode) node); return new CustomType(value); } } } Yaml yaml = new Yaml(new CustomTypeConstructor()); String yamlString = "!!str custom value"; CustomType customType = yaml.loadAs(yamlString, CustomType.class); Yaml yaml = new Yaml(); Node node = yaml.loadAs(yamlString, Node.class); node.setTag(Tag.MAP); public class CustomScalarExtension implements Extension { public void extend(Resolver resolver) { resolver.addImplicitResolver(new Tag("!custom"), Pattern.compile("^\\!custom"), "!"); } public void configure(DumperOptions options) {} public void configure(DumperOptions.ScalarStyle style) {} } yaml custom: !custom 123 public class CustomTypeConstructor extends BaseConstructor { public CustomTypeConstructor() { yamlConstructors.put(new Tag("!custom"), new ConstructCustomType()); } private class ConstructCustomType extends AbstractConstruct { public Object construct(Node node) { ScalarNode scalarNode = (ScalarNode) node; String value = scalarNode.getValue(); return new CustomType(value); } } } String yamlString = "custom: !custom 123"; Yaml yaml = new Yaml(new CustomTypeConstructor()); Map<String, Object> data = yaml.load(yamlString);


上一篇:
下一篇:
切换中文