我试图制作设置文件,但结果如下:
[
{
"name": "Test1",
"value": true
},
{
"name": "Test2",
"value": 1.7
}
]
我想要得到的是这样的:
{
"Test1": true,
"Test2": 1.7
}
如您所见,第二个要好得多,并且从中获取数据也更容易。
我正在将Setting Object转换为JSON,并将名称和值变量放入单独的元素中。
这是我的代码:
public class SettingsFile {
public ArrayList<Setting> settings = new ArrayList<>();
private Gson gson = new GsonBuilder().setPrettyPrinting().create();
private final String path;
public SettingsFile(String path) {
this.path = path;
}
public void save() {
try {
FileWriter fileWriter = new FileWriter(path);
gson.toJson(settings, fileWriter);
fileWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
这是设置类:
public class Setting<type> {
private type value;
private String name;
public Setting(String name) {
this.name = name;
}
public Setting<type> set(type value) {
this.value = value;
return this;
}
public type get() {
return value;
}
}
最佳答案
您可以使用Map
代替Setting
类,
ArrayList<Map<String, Object>> settings = new ArrayList<>();