首页 > 解决方案 > 属性文件到复杂的 JSON 字符串 [Java/Spring]

问题描述

我正在后端创建一个 Spring 应用程序,我的主要目标是管理*.properties文件中的属性(添加/更新/删除)。我想将此文件转换为 JSON,然后从 UI 应用程序对其进行操作。

有没有可能像这样转换结构:

a.x=1
a.y=2
b.z=3

像这样的 JSON:

{
    "a": {
        "x": 1,
        "y": 2
    },
    "b": {
        "z": 3
    }
}

我找到了使用 GSON 库的解决方案,但它为我创建了平面结构,而不是分层结构,我使用的代码:

Properties props = new Properties();
try (FileInputStream in = new FileInputStream(classPathResource.getFile())) {
    props.load(in);
}
String json = new GsonBuilder().enableComplexMapKeySerialization().create().toJson(props);

这里是否有人面临同样的问题并且可能为此找到了一个可行的项目?也许 GSON 库可以做到这一点?

标签: javajsonspringgson

解决方案


此解决方案确实涉及大量工作,但您将使用以下代码获得您想要实现的目标,基本上,这个想法是基于单个点拆分密钥,然后如果找到相同的第一个密钥,则创建一个 JsonObject。

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Properties;

import org.json.JSONObject;

import com.fasterxml.jackson.annotation.JsonIgnore;

public class SOTest {
    public static void main(String[] args) throws IOException {
        JSONObject jsonObject = new JSONObject();
        FileReader fileReader = new FileReader(new File("C:\\Usrc\\main\\java\\Sample.properties"));
        Properties properties = new Properties();
        properties.load(fileReader);
        Iterator<Entry<Object, Object>> iterator = properties.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<Object, Object> entry =  iterator.next();
            String value = (String) entry.getKey();
            String[] values = value.split("\\.");

            JSONObject opt = jsonObject.optJSONObject(values[0]);
            if(opt!=null) {
                opt.put(values[1],entry.getValue());
            }else {
                JSONObject object = new JSONObject();
                object.put(values[1], entry.getValue());
                jsonObject.put(values[0], object);
            }       
        }

        System.out.println(jsonObject.toString());  
    }
}

输出

{"a":{"x":"1","y":"3"},"b":{"z":"10"}}

推荐阅读