import ;
import ;
import ;
import ;
import ;
import .*;
import ;
/**
* @Auther: lisong
* @Date: 2021/3/12 17:35
* @Description:
*/
public class YmlUtils {
public static void main(String[] args) {
//第二个参数是生成YML文件,同样也可以不生成文件,直接输出内容
//输出到文件里面的内容和输出到控制台的内容是不一样的,有一点区别,这个需要注意。
//自己测试一下看看
readJsonAndCreateYaml("D:\\","D:\\");
}
/**
* 讀取json并生成yaml
*/
public static void readJsonAndCreateYaml(String json_url,String yaml_url) {
try {
String param = readJson(json_url);
createYaml(yaml_url,param);
} catch (Exception e) {
();
}
}
/**
* 將json轉化為yaml格式并生成yaml文件
* @param jsonString
* @return
* @throws JsonProcessingException
* @throws IOException
*/
@SuppressWarnings("unchecked")
public static void createYaml(String yaml_url,String jsonString) throws JsonProcessingException, IOException {
// parse JSON
JsonNode jsonNodeTree = new ObjectMapper().readTree(jsonString);
// save it as YAML
String jsonAsYaml = new YAMLMapper().writeValueAsString(jsonNodeTree);
Yaml yaml = new Yaml();
Map<String,Object> map = (Map<String, Object>) (jsonAsYaml);
createYamlFile(yaml_url, jsonAsYaml);
}
/**
* 将数据写入yaml文件
* @param url yaml文件路径
* @param data 需要写入的数据
*/
public static void createYamlFile(String url,String data){
Yaml yaml = new Yaml();
FileWriter writer;
try {
writer = new FileWriter(url);
String info = (data);
("-----------start--------------");
(info);
("-----------end--------------");
} catch (IOException e) {
();
}
}
/**
* 讀取json文件并返回字符串
*
* @param url
* @return
* @throws Exception
*/
@SuppressWarnings("resource")
public static String readJson(String url) throws Exception {
File file = new File(url);
FileReader fileReader = new FileReader(file);
BufferedReader bufReader = new BufferedReader(fileReader);
String message = new String();
String line = null;
while ((line = ()) != null) {
message += line;
}
return message;
}
}