java - 属性文件到复杂的 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 库可以做到这一点?
解决方案
此解决方案确实涉及大量工作,但您将使用以下代码获得您想要实现的目标,基本上,这个想法是基于单个点拆分密钥,然后如果找到相同的第一个密钥,则创建一个 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"}}
推荐阅读
- excel - 如何以更有效的方式在 VBA 中对色标进行条件格式化?
- vue.js - Nuxt.js 调用 axios 获取本地文件失败,出现 404。但是调用外部 URL 然后更改为本地文件有效
- sql-server - 更改此存储过程以避免使用 CROSS APPLY?
- r - Lavaan 模型输出问题:标签被截断
- git - spring-cloud-config-server - 无法合并远程主远程:空
- javascript - 具有相同 ID 的文本框的 TestCafe 选择器
- java - 反序列化 null 值以使用 Jackson 枚举
- python - 如何从输出分类器创建分割掩码?
- oracle - 是否可以在 DB System - Oracle Cloud 中为 Oracle Database 19c 配置 SSL?
- javascript - 在 JavaScript 中使用 await 时检查多个输入