当前位置:   article > 正文

java导出数据至yaml文件_dumperoptions 设置

dumperoptions 设置
文件通用操作:
  1. File yamlFile = new File(path);
  2. if(!yamlFile.exists()){
  3. yamlFile.mkdir();
  4. }
导出数据至yamlFile:
  1. // 是否使用文件追加的方式,true追加,false覆盖
  2. boolean isAppend =true;
  3. FileWriter fw = new FileWriter(yamlFile,isAppend);
  4. BufferedWriter buffer = new BufferedWriter(fw);
  5. DumperOptions dumperOptions = new DumperOptions();
  6. //设置FlowStyle
  7. dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
  8. //设置ScalarStyle
  9. dumperOptions.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
  10. Yaml yaml = new Yaml(dumperOptions);
  11. yaml.dump(data, buffer);

DumperOptions属性设置-FlowStyle

1.DumperOptions.FlowStyle.BLOCK

  1. !!com.demo.yaml.User
  2. address:
  3.   city: 济南
  4.   province: 山东
  5. hobbyList:
  6. - 游泳
  7. - 跑步
  8. password: '123456'
  9. phoneList:
  10. - number: '17603050528'
  11.   operator: 联通
  12. - number: '13612359876'
  13.   operator: 移动
  14. userId: '1'
  15. username: lisi

2.DumperOptions.FlowStyle.FLOW

!!com.demo.yaml.User {address: {city: 济南, province: 山东}, hobbyList: [游泳, 跑步], password: '123456',phoneList: [{number: '17603050528', operator: 联通}, {number: '13612359876', operator: 移动}], userId: '1', username: lisi}

3.DumperOptions.FlowStyle.AUTO

  1. !!com.demo.yaml.User
  2. address: {city: 济南, province: 山东}
  3. hobbyList: [游泳, 跑步]
  4. password: '123456'
  5. phoneList:
  6. - {number: '17603050528', operator: 联通}
  7. - {number: '13612359876', operator: 移动}
  8. userId: '1'
  9. username: lisi

DumperOptions属性设置-ScalarStyle

 1.DumperOptions.ScalarStyle.DOUBLE_QUOTED: 双引号
        key双引号,字符串值双引号

 2.DumperOptions.ScalarStyle.SINGLE_QUOTED: 单引号
        key单引号,字符串值单引号

 3.DumperOptions.ScalarStyle.LITERAL: 竖线 | 
        key双引号,value通过竖线分隔,竖线前显示数据类型

 4.DumperOptions.ScalarStyle.PLAIN(无)
        key没有引号,字符串值单引号

导入的数据为json类型

        使用java对象导入至yaml文件时无法保证字段顺序,且会将java全路径名也写进去(!!com.demo.yaml.User),解决方法可以在javaBean中的属性上面使用@JSONField注解,注解传入值name为导入yaml的key,ordinal为字段的顺序,

  1. @JSONField(name="stuName",ordinal=1)
  2. String name;
  3. @JSONField(name="age",ordinal=2)
  4. String age;

然后将java对象转化为JsonObject对象或者JsonAyyay对象,如果是JsonAyyay需要加一下下面的代码

  1. public static JSONArray parseArrayOrderly(String jsonStr){
  2. //JSON 默认排序
  3. int defaultParserFeature = JSON.DEFAULT_PARSER_FEATURE;
  4. //设置Feature.OrderedField 按照字符串中的顺序排序
  5. JSON.DEFAULT_PARSER_FEATURE = Feature.config(JSON.DEFAULT_PARSER_FEATURE, Feature.OrderedField, true);
  6. JSONArray jsonArray = JSONArray.parseArray(jsonStr);
  7. //JSON.DEFAULT_PARSER_FEATURE设置为全局设置 不确定影响范围,使用完还原默认值
  8. JSON.DEFAULT_PARSER_FEATURE = defaultParserFeature;
  9. return jsonArray;
  10. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/326282
推荐阅读
相关标签
  

闽ICP备14008679号