简体   繁体   English

如何从YAML文件中排除类?

[英]How to exclude class from YAML file?

I use SnakeYAML to persist data into YAML file. 我使用SnakeYAML将数据持久保存到YAML文件中。

DumperOptions options = new DumperOptions();
options.setPrettyFlow(true);
options.setAllowReadOnlyProperties(true);
Yaml yml = new Yaml(options);

FileWriter writer = new FileWriter(path);
yml.dump(object, writer);
writer.flush();
writer.close();

When I try to save the result, I get such content 当我尝试保存结果时,我得到了这样的内容

!!com.test.yml.User
users:
- {
  name: Bob,
  age: 14
}
- {
  name: John,
  age: 15
}

How can I avoid class !!com.test.yml.User from the file? 如何避免文件中的!!com.test.yml.User类?

Also I don't want to save null entities. 我也不想保存空实体。 For instance 例如

- {
    name: null,
    age: 14
  }

should be 应该

- {
    age: 14
  }
Representer representer = new Representer();
representer.addClassTag(com.test.yml.User.class, Tag.MAP);
Yaml yaml = new Yaml(representer);

This code says - please use Tag.MAP for the custom class User. 这段代码说-请为自定义类User使用Tag.MAP。 Since the MAP tag is implicit, the tag will disappear all together. 由于MAP标签是隐式的,因此该标签将一起消失。 But to parse it back you have to instruct SnakeYAML how to parse the data into User instance. 但是要解析它,您必须指示SnakeYAML如何将数据解析为User实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM