因为项目学习,看了一堆别人写的,运行出来出现一些花里胡哨的东西,所以自己就研究了一下,有用到数组,相对比较全。有问题欢迎提问。
用到的依赖:
<!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.66</version>
</dependency>
<!--json 转 yml -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.9.0.pr4</version>
</dependency>
/**
* 需要包
*/
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import com.alibaba.fastjson.JSON;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
/**
*主方法
*/
public static void getJson() throws Exception{
Map<String,Object> map = new LinkedHashMap<>();
List<Map<String,Object>> list = new ArrayList<>(); // 数组
List<Map<String,Object>> list1 = new ArrayList<>();
Map<String,Object> map1 = new LinkedHashMap<>();
Map<String,Object> map3 = new LinkedHashMap<>();
Map<String,Object> map4 = new LinkedHashMap<>();
Map<String,Object> map5 = new LinkedHashMap<>();
map.put("groups",list);
list.add(map1);
map1.put("name","monitor_base");
map1.put("rules",list1);
list1.add(map3);
map3.put("alert","CpuUsageAlert_waring");
map3.put("expr","sum(avg(irate(node_cpu_seconds_total{mode!='idle'}[5m])) without (cpu))by(instance)>0.60");
map3.put("for","2m");
map3.put("annotations",map5);
map4.put("level","warning");
map3.put("labels",map4);
map5.put("summary","Instance {{ $labels.instance }} CPU usage high");
map5.put("description","{{ $labels.instance }} CPU usage above 60% (current value: {{ $value }})");
System.out.println(map.toString());
JSON.toJSONString(map);
System.out.println(JSON.toJSONString(map));
// parse JSON
JsonNode jsonNodeTree = new ObjectMapper().readTree(JSON.toJSONString(map));
// save it as YAML
String jsonAsYaml = new YAMLMapper().writeValueAsString(jsonNodeTree);
Yaml yaml = new Yaml();
Map<String,Object> map6 = (Map<String, Object>) yaml.load(jsonAsYaml);
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml wyaml = new Yaml(dumperOptions);
File dumpfile = new File("D:\\b.yml"); //保存yaml
try(FileWriter writer = new FileWriter(dumpfile)) {
wyaml.dump(map, writer);
} catch (IOException e) {
e.printStackTrace();
}
}