Java工具封装:Yaml、Properties、Json三种内容格式之间互相转换

文章目录

      • 概述
      • 工具
          • 支持转换的形式
          • 代码
      • 测试
      • 可视化体验测试

概述

源码地址: https://github.com/FasterXML/jackson-dataformats-text

依赖

    
    <dependency>
      <groupId>com.fasterxml.jackson.dataformatgroupId>
      <artifactId>jackson-dataformat-yamlartifactId>
      <version>2.14.0-rc3version>
    dependency>

    
    <dependency>
      <groupId>com.fasterxml.jackson.dataformatgroupId>
      <artifactId>jackson-dataformat-propertiesartifactId>
      <version>2.14.0-rc3version>
    dependency>

    
    <dependency>
      <groupId>cn.hutoolgroupId>
      <artifactId>hutool-allartifactId>
      <version>5.8.7version>
    dependency>

工具

支持转换的形式
Yaml
Properties
json
代码
package work.linruchang.util;

import cn.hutool.core.bean.BeanPath;
import cn.hutool.core.comparator.CompareUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.javaprop.JavaPropsMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import com.fasterxml.jackson.dataformat.yaml.util.StringQuotingChecker;
import lombok.SneakyThrows;

import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * 内容转换工具类
 * @author LinRuChang
 * @version 1.0
 * @date 2022/11/03
 * @since 1.8
 **/
public class ContentConverUtil {

    private static ObjectMapper getYamlMappper() {
        YAMLFactory yamlFactory = YAMLFactory.builder()
                .enable(YAMLGenerator.Feature.MINIMIZE_QUOTES)
                .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER)
                .stringQuotingChecker(new StringQuotingChecker.Default() {
                    private static final long serialVersionUID = 1324053635146744895L;
                    @Override
                    public boolean needToQuoteValue(String value) {
                        return false;
                    }
                }).build();
        return new YAMLMapper(yamlFactory);
    }

    /**
     * properties转yaml
     * @param propertiesContent
     * @return
     */
    @SneakyThrows
    public static String propertiesToYaml(String propertiesContent) {
        if(StrUtil.isBlank(propertiesContent)) {return propertiesContent;}

        //仅有单层的map
        Properties properties = new Properties();
        properties.load(IoUtil.toStream(propertiesContent.getBytes(StandardCharsets.UTF_8)));

        //具体层级的Map
        Dict propertiesDict = Dict.create();
        properties.entrySet().stream()
                .sorted((mapEntry1,mapEntry2) -> -CompareUtil.compare(Convert.toStr(mapEntry1.getKey()).length(), Convert.toStr(mapEntry2.getKey()).length()))
                .forEach(mapEntry -> {
                    Object KeyName = mapEntry.getKey();
                    Object keyValue = mapEntry.getValue();
                    BeanPath.create(KeyName.toString()).set(propertiesDict,keyValue);
                });

        ObjectMapper yamlMapper = getYamlMappper();
        return yamlMapper.writeValueAsString(propertiesDict);
    }

    /**
     * yaml转properties
     * @param yamlContent
     * @return
     */
    @SneakyThrows
    public static String yamlToProperties(String yamlContent) {
        YAMLMapper yamlMapper = new YAMLMapper();

        JsonNode jsonNode = yamlMapper.readTree(yamlContent);
        JSONObject entries = JSONUtil.parseObj(jsonNode.toString());

        JavaPropsMapper mapper = new JavaPropsMapper();
        return mapper.writeValueAsString(entries);
    }


    /**
     * json转properties
     * @param json
     * @return
     */
    @SneakyThrows
    public static String jsonToProperties(String json) {
        if(JSONUtil.isTypeJSON(json)) {
            JavaPropsMapper javaPropsMapper = new JavaPropsMapper();
            JSONObject jsonObject = JSONUtil.parseObj(json);
            return javaPropsMapper.writeValueAsString(jsonObject);
        }
        return null;
    }

    /**
     * properties转json
     * @param propertiesContent
     * @return
     */
    @SneakyThrows
    public static String propertiesToJson(String propertiesContent) {
        if(StrUtil.isBlank(propertiesContent)) {return propertiesContent;}

        //仅有单层的map
        Properties properties = new Properties();
        properties.load(IoUtil.toStream(propertiesContent.getBytes(StandardCharsets.UTF_8)));

        //具体层级的Map
        Dict propertiesDict = Dict.create();
        properties.entrySet().stream()
                .sorted((mapEntry1,mapEntry2) -> -CompareUtil.compare(Convert.toStr(mapEntry1.getKey()).length(), Convert.toStr(mapEntry2.getKey()).length()))
                .forEach(mapEntry -> {
                    Object KeyName = mapEntry.getKey();
                    Object keyValue = mapEntry.getValue();
                    BeanPath.create(KeyName.toString()).set(propertiesDict,keyValue);
                });

        return JSONUtil.toJsonPrettyStr(propertiesDict);
    }


    /**
     * json转yaml
     * @param json
     * @return
     */
    @SneakyThrows
    public static String jsonToYaml(String json) {
        if(JSONUtil.isTypeJSON(json)) {
            ObjectMapper yamlMappper = getYamlMappper();
            JSONObject jsonObject = JSONUtil.parseObj(json);
            return yamlMappper.writeValueAsString(jsonObject);
        }
        return null;
    }

    /**
     * yaml转json
     * @param yaml
     * @return
     */
    @SneakyThrows
    public static String yamlToJson(String yaml) {
        if(StrUtil.isBlank(yaml)) { return yaml;}
        YAMLMapper yamlMapper = new YAMLMapper();
        JsonNode jsonNode = yamlMapper.readTree(yaml);
        return JSONUtil.formatJsonStr(jsonNode.toString());
    }

}

测试

package work.linruchang.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import junit.framework.TestCase;
import org.junit.Test;

public class ContentConverUtilTest extends TestCase {

    @Test
    public void testPropertiesToYaml() {
        String propertiesContent = FileUtil.readUtf8String("log4j.properties");
        String yamlContent = ContentConverUtil.propertiesToYaml(propertiesContent);

        Console.log("\n=====================");
        Console.log(yamlContent);
    }

    @Test
    public void testYamlToproperties() {
        String yamlContent = FileUtil.readUtf8String("application.yml");
        String propertiesContent = ContentConverUtil.yamlToProperties(yamlContent);

        Console.log("\n=====================");
        Console.log(propertiesContent);
    }

    public void testJsonToProperties() {
        String json = "{\"sourceLinkTitle\":\"Wuvrr Obin\",\"sourceUserIp\":\"Ffdt Cwd\",\"sourceLink\":\"Ay Ofnwy\",\"shortLink\":\"Fq Oudedzy\",\"user\":\"Mizexh Jg\",\"uuid\":\"Jvknghe Lmpdjx\",\"desc\":\"Usipnz Klu\"}";
        String properties = ContentConverUtil.jsonToProperties(json);
        Console.log(properties);
    }

    public void testJsonToYaml() {
        String json = "{\n" +
                "    \"abbreviationContent\": \"Xwj Nssxbd\",\n" +
                "    \"serialVersionUID\": -3099531488884144305,\n" +
                "    \"articleMetaInfo\":\n" +
                "    {\n" +
                "        \"serialVersionUID\": -1579979886629482564,\n" +
                "        \"publishedTime\": 875363642739,\n" +
                "        \"articleId\": -1437244485074535646,\n" +
                "        \"collectCount\": 629183334155589392,\n" +
                "        \"likeCount\": -3118592405612989804,\n" +
                "        \"readCount\": 4080532617418547847,\n" +
                "        \"userId\": 6338597020886381449,\n" +
                "        \"notLikeCount\": 3208017445759238918,\n" +
                "        \"commentCount\": -3213099621434702190\n" +
                "    },\n" +
                "    \"title\": \"Lwxiau Zmzxeya\",\n" +
                "    \"userId\": 8754570981951130505,\n" +
                "    \"contentType\": \"Vua Fzovw\",\n" +
                "    \"user\":\n" +
                "    {\n" +
                "        \"serialVersionUID\": -2507827799004706517,\n" +
                "        \"password\": \"Nhfdxey Nftdgkt\",\n" +
                "        \"loginName\": \"Bb Cm\",\n" +
                "        \"nickname\": \"Fpr Ihz\",\n" +
                "        \"motto\": \"Ueyzg Bebksqf\",\n" +
                "        \"userType\": \"Fqclpfl Direqbp\",\n" +
                "        \"headPortrait\": \"Cw Mhyf\",\n" +
                "        \"headPortraitType\": \"Edafmw Rqfqivy\",\n" +
                "        \"email\": \"Fhcl Jint\"\n" +
                "    },\n" +
                "    \"content\": \"Bzn Syiih\",\n" +
                "    \"articleCoversImg\": \"Qw Pdaz\",\n" +
                "    \"searchContent\": \"Bmckui Nph\"\n" +
                "}";
        String yaml = ContentConverUtil.jsonToYaml(json);
        Console.log(yaml);
    }

    public void testYamlToJson() {
        String yamlContent = FileUtil.readUtf8String("application.yml");
        String s = ContentConverUtil.yamlToJson(yamlContent);
        Console.log(s);
    }

    public void testPropertiesToJson() {
        String propertiesContent = FileUtil.readUtf8String("log4j.properties");

        String json = ContentConverUtil.propertiesToJson(propertiesContent);

        Console.log(json);
    }
}

可视化体验测试

个人在线网站:http://qq.linruchang.work/lrc-utils-web/#/generate-code

Java工具封装:Yaml、Properties、Json三种内容格式之间互相转换_第1张图片

Java工具封装:Yaml、Properties、Json三种内容格式之间互相转换_第2张图片

你可能感兴趣的:(Java,java,json,Yaml,Properties,内容转换)