将一个对象生成yaml文件时,如何去掉自定义对象后面自带的!! 类路径信息,是此次分享的内容,举例以下内容。
1.首先定义一个yaml类,用来配置类信息等内容(核心配置)
private static Yaml getYamlRepresenter(){
Constructor constructor = new Constructor(User.class);//主类对象
TypeDescription carDescription = new TypeDescription(User.class);
carDescription.putListPropertyType("Address", Address.class); //属性类对象
carDescription.putListPropertyType("Model", Model.class); //属性类对象
constructor.addTypeDescription(carDescription);
Representer representer = new Representer();
// 好像是设置空属性填充
//representer.getPropertyUtils().setSkipMissingProperties(true);
//会使用 User 对map的类型进行解析,不会生成!!和包路径
representer.addClassTag(User.class, Tag.MAP); //配合上面使用,将map值解析为对应的类
representer.addClassTag(Address.class, Tag.MAP);
representer.addClassTag(Model.class, Tag.MAP);
final DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); //块状格式
options.setExplicitStart(false);
options.setIndicatorIndent(2);
options.setSplitLines(true);
options.setIndent(4);
Yaml yaml = new Yaml(constructor,representer,options);
return yaml;
}
2.构造主要的dump方法(根据需要可选其他方法,这里使用dump)
public static void dumpFileRepresenter(File file, Map data) throws IOException {
OutputStreamWriter writer = new FileWriter(file);
getYamlRepresenter().dump(data, writer);
}
3.创建具体的yaml文件方法
/**
* 创建yaml的配置文件
* @param filePath 路径
* @param fileName 文件名
* @param mapData 生成yaml的数据
* @throws IOException
*/
public File makeYamlFileGetPath(String filePath, String fileName, Map<String,Object> mapData) throws IOException {
File file = new File(filePath, fileName);
FileUtils.forceMkdir(file.getParentFile());
YamlUtil.dumpFileRepresenter(file,mapData);
logger.info("yaml dump path {}",file.getAbsolutePath()); //打印了一下本地文件生成的地址信息
return file;
}
4.简单列出主类信息作参考
public class User {
private String name;
private Address address;
private List<Model> mode;
private Integer age;
}
5.生成文件展示
address:
enabled: false
address_config: address.yaml
name: test01
age: 66
model:
framework: tensorflow
input_features:
- pclass
- plib
- pnum
model_config: model.conf