java - 属性文件到复杂的 JSON 字符串 [Java/Spring]

标签 java json spring gson

我正在后端创建一个 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 库可以做到这一点?

最佳答案

这个解决方案确实涉及大量工作,但是使用下面的代码你会得到你想要实现的目标,基本上,这个想法是基于单个点分割 key ,然后如果相同的第一个 key 是创建一个 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"}}

关于java - 属性文件到复杂的 JSON 字符串 [Java/Spring],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58266423/

相关文章:

javascript - Ajax 请求,格式化结果时,如果我添加超过 2 行代码,某些元素会失败

java - 无法获取 JDBC 连接;嵌套异常是 java.sql.SQLException Mule ESB

java - 使用 Spring Data 审计数据库记录更改

java - 在 ConcurrentHashMap 中创建多个键而不是一个键

java - 在 Android 上以编程方式创建 View 样式

json - 用 JSON 或其他东西在网页中生成 POSTMAN

iOS Swift Alamofire JSON 响应返回 Bool 值 `1` 或 `0`

java - URL 和方法的 spring 安全设置

java - 错误: package ‘XLConnectJars’ could not be loaded in mac os

java - 在 Swing 的 JTextPane 中设置选项卡策略