赞
踩
- File yamlFile = new File(path);
- if(!yamlFile.exists()){
- yamlFile.mkdir();
- }
- // 是否使用文件追加的方式,true追加,false覆盖
- boolean isAppend =true;
- FileWriter fw = new FileWriter(yamlFile,isAppend);
- BufferedWriter buffer = new BufferedWriter(fw);
- DumperOptions dumperOptions = new DumperOptions();
- //设置FlowStyle
- dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
- //设置ScalarStyle
- dumperOptions.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
- Yaml yaml = new Yaml(dumperOptions);
- yaml.dump(data, buffer);
DumperOptions属性设置-FlowStyle
1.DumperOptions.FlowStyle.BLOCK
- !!com.demo.yaml.User
- address:
- city: 济南
- province: 山东
- hobbyList:
- - 游泳
- - 跑步
- password: '123456'
- phoneList:
- - number: '17603050528'
- operator: 联通
- - number: '13612359876'
- operator: 移动
- userId: '1'
- 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
- !!com.demo.yaml.User
- address: {city: 济南, province: 山东}
- hobbyList: [游泳, 跑步]
- password: '123456'
- phoneList:
- - {number: '17603050528', operator: 联通}
- - {number: '13612359876', operator: 移动}
- userId: '1'
- 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为字段的顺序,
- @JSONField(name="stuName",ordinal=1)
- String name;
- @JSONField(name="age",ordinal=2)
- String age;
然后将java对象转化为JsonObject对象或者JsonAyyay对象,如果是JsonAyyay需要加一下下面的代码
- public static JSONArray parseArrayOrderly(String jsonStr){
- //JSON 默认排序
- int defaultParserFeature = JSON.DEFAULT_PARSER_FEATURE;
- //设置Feature.OrderedField 按照字符串中的顺序排序
- JSON.DEFAULT_PARSER_FEATURE = Feature.config(JSON.DEFAULT_PARSER_FEATURE, Feature.OrderedField, true);
- JSONArray jsonArray = JSONArray.parseArray(jsonStr);
- //JSON.DEFAULT_PARSER_FEATURE设置为全局设置 不确定影响范围,使用完还原默认值
- JSON.DEFAULT_PARSER_FEATURE = defaultParserFeature;
- return jsonArray;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。