【原创】yaml转换成JSON、MAP、Properties

26 篇文章 0 订阅


yaml读取和解析太麻烦,转换成JSON、MAP、Properties等处理就方便很多!

引入依赖包

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

编写工具类


import java.io.IOException;
import java.util.Map;
import java.util.Properties;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.dataformat.javaprop.JavaPropsMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;

/**
 * 
 * yaml转换工具
 * 
 * @author 00fly
 * @version [版本号, 2023年4月25日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public final class YamlUtils
{
    private static YAMLMapper yamlMapper = new YAMLMapper();
    
    private static JavaPropsMapper javaPropsMapper = new JavaPropsMapper();
    
    private YamlUtils()
    {
        super();
    }
    
    /**
     * yaml转properties
     * 
     * @param yamlContent
     * @return
     * @throws IOException
     */
    public static Properties yamlToProperties(String yamlContent)
        throws IOException
    {
        JsonNode jsonNode = yamlMapper.readTree(yamlContent);
        return javaPropsMapper.writeValueAsProperties(jsonNode);
    }
    
    /**
     * yaml转Map<String, String>
     * 
     * @param yamlContent
     * @return
     * @throws IOException
     */
    public static Map<String, String> yamlToMap(String yamlContent)
        throws IOException
    {
        JsonNode jsonNode = yamlMapper.readTree(yamlContent);
        return javaPropsMapper.writeValueAsMap(jsonNode);
    }
    
    /**
     * yaml转properties字符串
     * 
     * @param yamlContent
     * @return
     * @throws JsonMappingException
     * @throws JsonProcessingException
     */
    public static String yamlToPropText(String yamlContent)
        throws JsonMappingException, JsonProcessingException
    {
        JsonNode jsonNode = yamlMapper.readTree(yamlContent);
        return javaPropsMapper.writeValueAsString(jsonNode);
    }
    
    /**
     * yaml转Json字符串
     * 
     * @param yamlContent
     * @return
     * @throws JsonMappingException
     * @throws JsonProcessingException
     */
    public static String yamlToJson(String yamlContent)
        throws JsonMappingException, JsonProcessingException
    {
        JsonNode jsonNode = yamlMapper.readTree(yamlContent);
        return jsonNode.toPrettyString();
    }
}

单元测试代码


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.DefaultPropertiesPersister;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class YamlUtilsTest
{
    String yamlContent;
    
    @Before
    public void setup()
    {
        try
        {
            Resource resource = new ClassPathResource("application.yml");
            yamlContent = FileUtils.readFileToString(resource.getFile(), StandardCharsets.UTF_8.toString());
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
        }
    }
    
    @Test
    public void yamlToPropertiesTest()
        throws IOException
    {
        Properties properties = YamlUtils.yamlToProperties(yamlContent);
        log.info("yamlToProperties: {}", properties);
    }
    
    @Test
    public void yamlToPropertiesTest2()
        throws IOException
    {
        // yaml->String->Properties
        String propText = YamlUtils.yamlToPropText(yamlContent);
        DefaultPropertiesPersister propertiesPersister = new DefaultPropertiesPersister();
        Properties props = new Properties();
        propertiesPersister.load(props, new ByteArrayInputStream(propText.getBytes()));
        log.info("yamlToProperties: {}", props);
    }
    
    @Test
    public void yamlToMap()
        throws IOException
    {
        Map<String, String> map = YamlUtils.yamlToMap(yamlContent);
        log.info("yamlToMap: {}", map);
    }
    
    @Test
    public void yamlToPropText()
        throws IOException
    {
        String text = YamlUtils.yamlToPropText(yamlContent);
        log.info("yamlToPropText: {}", text);
    }
    
    @Test
    public void yamlToJson()
        throws IOException
    {
        String json = YamlUtils.yamlToJson(yamlContent);
        log.info("yamlToJson: {}", json);
    }
}

测试文件

application.yml

server:
  port: 8082
  servlet:
    context-path: /
    session:
      timeout: 1800
spring:
  datasource:
    url: ${druid.url}
    username: ${druid.username}
    password: ${druid.password}
    driverClassName: ${druid.driverClassName}
    type: com.alibaba.druid.pool.DruidDataSource
    sqlScriptEncoding: utf-8
    initialization-mode: embedded
    schema: classpath:schema.sql
  profiles:
    active:
    - dev
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 100MB
knife4j:
  enable: true
logging:
  level:
    root: info
    org.springframework.web: info

测试结果

04-27 10:12:38.918 [main] INFO  com.fly.core.utils.YamlUtilsTest - yamlToMap: {server.port=8082, server.servlet.context-path=/, server.servlet.session.timeout=1800, spring.datasource.url=${druid.url}, spring.datasource.username=${druid.username}, spring.datasource.password=${druid.password}, spring.datasource.driverClassName=${druid.driverClassName}, spring.datasource.type=com.alibaba.druid.pool.DruidDataSource, spring.datasource.sqlScriptEncoding=utf-8, spring.datasource.initialization-mode=embedded, spring.datasource.schema=classpath:schema.sql, spring.profiles.active.1=dev, spring.servlet.multipart.max-file-size=10MB, spring.servlet.multipart.max-request-size=100MB, knife4j.enable=true, logging.level.root=info, logging.level.org.springframework.web=info}
04-27 10:12:38.932 [main] INFO  com.fly.core.utils.YamlUtilsTest - yamlToJson: {
  "server" : {
    "port" : 8082,
    "servlet" : {
      "context-path" : "/",
      "session" : {
        "timeout" : 1800
      }
    }
  },
  "spring" : {
    "datasource" : {
      "url" : "${druid.url}",
      "username" : "${druid.username}",
      "password" : "${druid.password}",
      "driverClassName" : "${druid.driverClassName}",
      "type" : "com.alibaba.druid.pool.DruidDataSource",
      "sqlScriptEncoding" : "utf-8",
      "initialization-mode" : "embedded",
      "schema" : "classpath:schema.sql"
    },
    "profiles" : {
      "active" : [ "dev" ]
    },
    "servlet" : {
      "multipart" : {
        "max-file-size" : "10MB",
        "max-request-size" : "100MB"
      }
    }
  },
  "knife4j" : {
    "enable" : true
  },
  "logging" : {
    "level" : {
      "root" : "info",
      "org.springframework.web" : "info"
    }
  }
}
04-27 10:12:38.937 [main] INFO  com.fly.core.utils.YamlUtilsTest - yamlToProperties: {logging.level.org.springframework.web=info, spring.datasource.schema=classpath:schema.sql, spring.datasource.url=${druid.url}, server.servlet.session.timeout=1800, spring.datasource.username=${druid.username}, logging.level.root=info, spring.servlet.multipart.max-request-size=100MB, spring.datasource.initialization-mode=embedded, server.servlet.context-path=/, spring.datasource.driverClassName=${druid.driverClassName}, spring.datasource.sqlScriptEncoding=utf-8, server.port=8082, spring.datasource.password=${druid.password}, knife4j.enable=true, spring.profiles.active.1=dev, spring.servlet.multipart.max-file-size=10MB, spring.datasource.type=com.alibaba.druid.pool.DruidDataSource}
04-27 10:12:38.939 [main] INFO  com.fly.core.utils.YamlUtilsTest - yamlToProperties: {logging.level.org.springframework.web=info, spring.datasource.schema=classpath:schema.sql, spring.datasource.url=${druid.url}, server.servlet.session.timeout=1800, spring.datasource.username=${druid.username}, logging.level.root=info, spring.servlet.multipart.max-request-size=100MB, spring.datasource.initialization-mode=embedded, server.servlet.context-path=/, spring.datasource.driverClassName=${druid.driverClassName}, spring.datasource.sqlScriptEncoding=utf-8, server.port=8082, spring.datasource.password=${druid.password}, knife4j.enable=true, spring.profiles.active.1=dev, spring.servlet.multipart.max-file-size=10MB, spring.datasource.type=com.alibaba.druid.pool.DruidDataSource}
04-27 10:12:38.943 [main] INFO  com.fly.core.utils.YamlUtilsTest - yamlToPropText: server.port=8082
server.servlet.context-path=/
server.servlet.session.timeout=1800
spring.datasource.url=${druid.url}
spring.datasource.username=${druid.username}
spring.datasource.password=${druid.password}
spring.datasource.driverClassName=${druid.driverClassName}
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.sqlScriptEncoding=utf-8
spring.datasource.initialization-mode=embedded
spring.datasource.schema=classpath:schema.sql
spring.profiles.active.1=dev
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=100MB
knife4j.enable=true
logging.level.root=info
logging.level.org.springframework.web=info

反向转换


/**
 * Properties 转换工具
 * 
 * @author 00fly
 *
 */
public class PropertiesUtils
{
    private static YAMLMapper yamlMapper = new YAMLMapper();
    
    private static JavaPropsMapper javaPropsMapper = new JavaPropsMapper();
    
    /**
     * properties对象转Json字符串
     * 
     * @param properties对象
     * @return
     * @throws IOException
     */
    public static String propertiesToJson(Properties properties)
        throws IOException
    {
        JsonNode jsonNode = javaPropsMapper.readPropertiesAs(properties, JsonNode.class);
        return jsonNode.toPrettyString();
    }
    
    /**
     * properties对象转yaml
     * 
     * @param properties对象
     * @return
     * @throws IOException
     */
    public static String propertiesToYaml(Properties properties)
        throws IOException
    {
        JsonNode jsonNode = javaPropsMapper.readPropertiesAs(properties, JsonNode.class);
        return yamlMapper.writeValueAsString(jsonNode);
    }
    
    /**
     * properties字符串转Json字符串
     * 
     * @param propText
     * @return
     * @throws IOException
     */
    public static String propTextToJson(String propText)
        throws IOException
    {
        JsonNode jsonNode = javaPropsMapper.readTree(propText);
        return jsonNode.toPrettyString();
    }
    
    /**
     * properties字符串转yaml
     * 
     * @param propText
     * @return
     * @throws IOException
     */
    public static String propTextToYaml(String propText)
        throws IOException
    {
        JsonNode jsonNode = javaPropsMapper.readTree(propText);
        return yamlMapper.writeValueAsString(jsonNode);
    }
    
    private PropertiesUtils()
    {
        super();
    }
}

在这里插入图片描述

源码传送

https://gitee.com/00fly/effict-side/tree/master/springboot-hello/src/main/java/com/fly/core/utils

– over –

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值