springboot中如何实现JSON字符串转换为YAML呢?
下文笔者讲述Springboot中JSON字符串转YAML的方法及示例分享
JSON转YAML的实现思路
1.引入依赖 2.使用 new YAMLMapper().writeValueAsString(JSONNode) 方法即可将json字符串转换为YAML例:JSON转YAML的示例
//添加依赖 <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> <version>2.6.5</version> </dependency> //业务逻辑代码 //读取 JSON 字符串 JsonNode jsonNodeTree = new ObjectMapper().readTree(jsonStr); //转换成 YAML 字符串 String yamlStr = new YAMLMapper().writeValueAsString(jsonNodeTree); 效果展示 --- apiVersion: "app.alauda.io/v1alpha1" kind: "HelmRequest" metadata: name: "mongodb-java-6666" spec: chart: "bitnami/mongodb" namespace: "test-hl2" releaseName: "mongodb-java-6666" values: service: type: "NodePort" auth: rootUser: "admin" rootPassword: "admin123123" version: "11.0.4"
方式2:JSON转YAML
//添加依赖 <dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.18</version> </dependency> //业务逻辑代码 Yaml yaml = new Yaml(); //将 JSON 字符串转成 Map Map<String,Object> map = (Map<String, Object>) yaml.load(jsonUrl); //转换成 YAML 字符串 String yamlStr = yaml.dumpAsMap(map); 效果展示 kind: Service apiVersion: v1 metadata: name: tomcat labels: app: tomcat spec: ports: - name: tcp-8080 protocol: TCP port: 8080 selector: app: tomcat
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。