Java Json和yaml转换

在开发过程中json格式的字符串用的是最多的,但是有时候也会遇到yaml格式的字符串;比如k8s的开发中创建资源的时候都是使用yaml去创建,如果api支持json的字符串创建还好,不能支持json格式就只能将对应资源的信息转为yaml格式的字符串了。

一、导入需要的包

yaml转json相关的包(snakeyaml包)
如果项目中导入了 spring-boot-starter 包,其中已经包含了 snakeyaml 包

<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.19</version>
</dependency>

hutool相关的包(这里主要用于json处理)
一般项目中也会导入该包使用该包的其他常用功能;比如字符串、集合相关功能

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.2</version>
</dependency>

下面两个包用于将json转为yaml时使用

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.1</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
    <version>2.13.1</version>
</dependency>

二、代码

package com.test.yaml;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import org.yaml.snakeyaml.Yaml;

import java.util.ArrayList;
import java.util.List;

/**
 * json yaml转换类
 */
public class JsonYamlUtil {

    /**
     * yaml字符串转json字符串
     * @param yamlString
     * @return
     */
    public static List<String> yamlConverToJson(String yamlString){
        Yaml yaml = new Yaml();
        //yaml中可以通过 --- 实现同一个yaml中配置多个资源,loadAll会根据 --- 进行拆分,生成多个对象,所以是List
        Iterable<Object> object = yaml.loadAll(yamlString);
        List<String> yamlList = new ArrayList<>();
        object.forEach(y -> {
            if (ObjectUtil.isNotNull(y)) {
                yamlList.add(JSONUtil.toJsonStr(y));
            }
        });
        return yamlList;
    }

    /**
     * json字符串转yaml字符串
     * @param jsonString
     * @return
     */
    public static String jsonConverToYaml(String jsonString) throws JsonProcessingException {
        JsonNode jsonNode = new ObjectMapper().readTree(jsonString);
        String string = new YAMLMapper().writeValueAsString(jsonNode);
        //因为writeValueAsString生成的yaml字符串会带有 ---\n 所以进行替换操作
        String replaceAll = string.replaceAll("---\n", "");
        return replaceAll;
    }

}

测试代码

package com.test.yaml;

import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.List;

public class Test {
    public static void main(String[] args) throws JsonProcessingException {

        String yamlString = "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: nginx-deployment\nspec:\n  selector:\n    " +
                "matchLabels:\n      app: nginx\n  replicas: 2 # tells deployment to run 2 pods matching the template\n  template:\n    " +
                "metadata:\n      labels:\n        app: nginx\n    spec:\n      containers:\n      - name: nginx\n        " +
                "image: nginx:1.14.2\n        ports:\n        - containerPort: 80\n---\napiVersion: v1\nkind: Service\nmetadata:\n  " +
                "name: my-service\nspec:\n  selector:\n    app: nginx\n  ports:\n    - protocol: TCP\n      port: 80\n      targetPort: 80";
        List<String> yamlList = JsonYamlUtil.yamlConverToJson(yamlString);
        for (String yaml : yamlList) {
            System.out.println("yaml转json:"+yaml);
        }
        for (String yaml : yamlList) {
            String jsonConverToYaml = JsonYamlUtil.jsonConverToYaml(yaml);
            System.out.println("json转yaml:\n"+jsonConverToYaml);
        }
    }
}

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值