栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java Json和yaml转换

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java Json和yaml转换

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

一、导入需要的包

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


    org.yaml
    snakeyaml
    1.19

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


    cn.hutool
    hutool-all
    5.8.2

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


    com.fasterxml.jackson.core
    jackson-databind
    2.13.1



    com.fasterxml.jackson.dataformat
    jackson-dataformat-yaml
    2.13.1

二、代码
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;


public class JsonYamlUtil {

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

    
    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/v1nkind: Deploymentnmetadata:n  name: nginx-deploymentnspec:n  selector:n    " +
                "matchLabels:n      app: nginxn  replicas: 2 # tells deployment to run 2 pods matching the templaten  template:n    " +
                "metadata:n      labels:n        app: nginxn    spec:n      containers:n      - name: nginxn        " +
                "image: nginx:1.14.2n        ports:n        - containerPort: 80n---napiVersion: v1nkind: Servicenmetadata:n  " +
                "name: my-servicenspec:n  selector:n    app: nginxn  ports:n    - protocol: TCPn      port: 80n      targetPort: 80";
        List 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);
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号