yml与json互转、yaml转json、json转yml

yml与json互转、yaml转json、json转yml

使用jackson下的格式化模块实现
依赖:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
    <version>2.13.3</version>
</dependency>
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;

/**
 * @author lingkang
 * Created by 2022/5/26
 */
public class YamlDemo {
    public static void main(String[] args) throws Exception{
        String yaml="spring:\n" +
                "  datasource:\n" +
                "    driver-class-name: com.mysql.cj.jdbc.Driver\n" +
                "    url: jdbc:mysql://127.0.0.1:3306/yue?useUnicode=true\n" +
                "    username: root\n" +
                "    password: 123456";

        // yaml转json
        Object obj = new ObjectMapper(new YAMLFactory()).readValue(yaml, Object.class);
        String json = new ObjectMapper().writeValueAsString(obj);
        System.out.println(json);

        // json转yaml
        String yamlOutput = new YAMLMapper().writeValueAsString(new ObjectMapper().readTree(json));
        System.out.println(yamlOutput);
    }
}

效果展示
在这里插入图片描述

posted @ 2022-09-16 00:08  凌康  阅读(599)  评论(0编辑  收藏  举报