我有一个如下所示的单例类
public class Config {
private static Config instance;
int weight;
String color;
private Config(){}
public static Config getInstance(){
if (null == instance) {
instance = new Config();
}
return instance;
}
public String getColor(){
return color;
}
public int getWeight(){
return weight;
}
}
我想要做的是创建一个如下所示的 JSON 文件:
{"weight":22,"color":#RRGGBB}
然后从文件中提取权重和颜色的值,然后在我的类中为变量 String color 和 int Weight 设置这两个值。 我尝试过类似的事情:
FileInputStream fileIn = new FileInputStream("./config.json");
ObjectInputStream in = new ObjectInputStream(fileIn);
json = gson.toJson(in.readObject());
Config.getInstance() = gson.fromJson(json,Config.class); //?????
我遇到的问题是最后一行代码。我不明白如何使用 fromJson() 函数使其与单例类实例一起使用。
我想输出这样的内容
System.out.println(Config.getInstance().getColor()+ " "+ Config.getInstance().getWeight());
得到这样的结果:
#RRGGBB 22
有什么方法可以让 is 工作吗?有没有更好的方法呢?预先感谢您!
最佳答案
你可以做类似的事情
Config configFromGson = gson.fromJson(json, Config.class);
// set values in singleton config
config.getInstance().setColor(configFromGson.getColor());
config.getInstance().setWeight(configFromGson.getWeight());
关于java - 从 JSON 文件获取信息并在单例类的属性中使用该数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61868851/