使用Java将yaml转为properties,保证顺序、实测无BUG版本

使用Java将yaml转为properties

    • [一、 前言](#一、 前言)
      • [1.1 顺序错乱的原因](#1.1 顺序错乱的原因)
      • [1.2 遗漏子节点的原因](#1.2 遗漏子节点的原因)
    • 二、优化措施
    • 三、源码

一、 前言

浏览了一圈网上的版本,大多存在以下问题:

  • 转换后顺序错乱
  • 遗漏子节点

基于此进行了优化,如果只是想直接转换,可直接使用我发布的 在线版本

如果想在工程中使用,可继续往下看,源码在文末。

1.1 顺序错乱的原因

大部分代码都是使用了java.util.Properties类来转换,这个类是基于ConcurrentHashMap来存储键值对的,必然会顺序错乱

这是截取的Properties类的部分源码:

java 复制代码
/**
  * Properties does not store values in its inherited Hashtable, but instead
  * in an internal ConcurrentHashMap.  Synchronization is omitted from
  * simple read operations.  Writes and bulk operations remain synchronized,
  * as in Hashtable.
  */
private transient volatile ConcurrentHashMap<Object, Object> map;

/**
     * Creates an empty property list with the specified defaults.
     *
     * @implNote The initial capacity of a {@code Properties} object created
     * with this constructor is unspecified.
     *
     * @param   defaults   the defaults.
     */
public Properties(Properties defaults) {
    this(defaults, 8);
}

private Properties(Properties defaults, int initialCapacity) {
    // use package-private constructor to
    // initialize unused fields with dummy values
    super((Void) null);
    map = new ConcurrentHashMap<>(initialCapacity);
    this.defaults = defaults;

    // Ensure writes can't be reordered
    UNSAFE.storeFence();
}

1.2 遗漏子节点的原因

主要还是代码不够严谨,解析的时候没有判断子节点是否是数组或对象,粗暴的转为String直接赋值了

二、优化措施

  • 基于LinkedHashMap来存储键值对

  • 递归遍历时判断子节点类型,不同类型采用不同的处理方式

三、源码

java 复制代码
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class YamlUtil {

    /**
     * yaml 转 Properties
     *
     * @param input
     * @return
     */
    public static String castToProperties(String input) {
        Map<String, Object> propertiesMap = new LinkedHashMap<>();
        Map<String, Object> yamlMap = new Yaml().load(input);
        flattenMap("", yamlMap, propertiesMap);
        StringBuffer strBuff = new StringBuffer();
        propertiesMap.forEach((key, value) -> strBuff.append(key)
                .append("=")
                .append(value)
                .append(StrUtil.LF));
        return strBuff.toString();
    }

    /**
     * 递归 Map 集合,转为 Properties集合
     *
     * @param prefix
     * @param yamlMap
     * @param treeMap
     */
    private static void flattenMap(String prefix, Map<String, Object> yamlMap, Map<String, Object> treeMap) {
        yamlMap.forEach((key, value) -> {
            String fullKey = prefix + key;
            if (value instanceof LinkedHashMap) {
                flattenMap(fullKey + ".", (LinkedHashMap) value, treeMap);
            } else if (value instanceof ArrayList) {
                List values = (ArrayList) value;
                for (int i = 0; i < values.size(); i++) {
                    String itemKey = String.format("%s[%d]", fullKey, i);
                    Object itemValue = values.get(i);
                    if (itemValue instanceof String) {
                        treeMap.put(itemKey, itemValue);
                    } else {
                        flattenMap(itemKey + ".", (LinkedHashMap) itemValue, treeMap);
                    }
                }
            } else {
                treeMap.put(fullKey, value.toString());
            }
        });
    }

}
相关推荐
爱吃山竹的大肚肚10 分钟前
文件上传大小超过服务器限制
java·数据库·spring boot·mysql·spring
黄昏恋慕黎明10 分钟前
测试模型讲解
java
瑞雪兆丰年兮13 分钟前
[从0开始学Java|第十二天]学生管理系统升级
java·开发语言
弹简特13 分钟前
【JavaSE-网络部分03】网络原理-泛泛介绍各个层次
java·开发语言·网络
周杰伦的稻香13 分钟前
Hexo搭建教程
java·node.js
倔强的石头10614 分钟前
飞算JavaAI如何提升重塑Java开发体验
java·飞算javaai·ai开发工具
努力d小白17 分钟前
leetcode438.找到字符串中所有字母异位词
java·javascript·算法
短剑重铸之日17 分钟前
《设计模式》第九篇:三大类型之结构型模式
java·后端·设计模式·组合模式·代理模式·结构性模式
没有bug.的程序员19 分钟前
RocketMQ 与 Kafka 深度对垒:分布式消息引擎内核、事务金融级实战与高可用演进指南
java·分布式·kafka·rocketmq·分布式消息·引擎内核·事务金融
jiang_changsheng20 分钟前
工作流agent汇总分析 2
java·人工智能·git·python·机器学习·github·语音识别