我正在后端创建一个 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/