SnakeYAML序列化时去掉!!类路径信息

        将一个对象生成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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值