# private User john john:# field name id:13# bean's field name:John# bean's field nickName:Bobi# 不能写为 nick-name,这是因为 Spring Boot 作了特殊处理
# private List<User> users # 对象数组使用下面 2 种格式都可以 users: -id:14# bean's field name:Jack# bean's field - id:15 name:Sophie
# private Map<String, User> userMap userMap:# field name (注意不能用 user-map,这种方式是 SpringBoot 对 Yaml 进行了改造) Alice:# map key id:10# map value is bean, bean's field name:Alice# map value is bean, bean's field Bob: id:11 name:Bob
publicstaticvoidunmarshalUserTest1(){ Yaml yaml = new Yaml(new Constructor(User.class)); InputStream in = ClassLoader.getSystemResourceAsStream("user.yml"); // 找不到返回 null User user = yaml.load(in);
System.out.println(JSON.toJSONString(user)); }
publicstaticvoidunmarshalUserTest2()throws IOException { Yaml yaml = new Yaml(); InputStream in = ClassLoader.getSystemResourceAsStream("user.yml"); // 找不到返回 null User user = yaml.loadAs(in, User.class);
System.out.println(JSON.toJSONString(user)); }
publicstaticvoidunmarshalUserHolderTest(){ Yaml yaml = new Yaml(new Constructor(UserHolder.class)); InputStream in = ClassLoader.getSystemResourceAsStream("user-holder.yml"); UserHolder user = yaml.load(in);