Hi,
I’m trying to save several variables to a file so I can reload them when the program opens. I manage to create a JSON file but I have to manually add the code, I would like to automate this by adding in an Array, the variables that I would like to save and recall. I managed to save my variables in a JSON file but I can’t extract these values to reassign them to variables.
Old code that is working :
json = new JSONObject();
json.setInt("Mode", Mode);
json.setInt("PortServeur", PortServeur);
json.setString("IpRP1", IpRP1);
json.setInt("PortRP1", PortRP1);
json.setString("IpRP2", IpRP2);
json.setInt("PortRP2", PortRP2);
json.setString("IpRP3", IpRP3);
json.setInt("PortRP3", PortRP3);
json.setString("IpRP4", IpRP4);
json.setInt("PortRP4", PortRP4);
json.setString("IpLive", IpLive);
json.setInt("PortLive", PortLive);
json.setInt("DureePenalite", DureePenalite);
saveJSONObject(json, "data/config.json");
void setup() {
// Load JSON
json = loadJSONObject("config.json");
Mode = json.getInt("Mode");
PortServeur = json.getInt("PortServeur");
IpRP1 = json.getString("IpRP1");
PortRP1 = json.getInt("PortRP1");
IpRP2 = json.getString("IpRP2");
PortRP2 = json.getInt("PortRP2");
IpLive = json.getString("IpLive");
PortLive = json.getInt("PortLive");
...
New code trying to automate (the names of the variables have changed in the meantime) :
void saveConfig() {
int[] JsonIntValeur = { Mode, PortServeur, PortBuzzer1, PortBuzzer2, PortBuzzer3, PortBuzzer4, PortLive, PortMoniteur1, PortMoniteur2, DureePenalite};
String[] JsonStringValeur = { IpBuzzer1, IpBuzzer2, IpBuzzer3, IpBuzzer4, IpLive, IpMoniteur1, IpMoniteur2};
JSONArray valuesInt = new JSONArray();
JSONArray valuesString = new JSONArray();
for (int i = 0; i < JsonIntValeur.length; i++) {
JSONObject config = new JSONObject();
config.setInt(JsonIntNom[i], JsonIntValeur[i]);
valuesInt.setJSONObject(i, config);
}
for (int i = 0; i < JsonStringValeur.length; i++) {
JSONObject config2 = new JSONObject();
config2.setString(JsonStringNom[i], JsonStringValeur[i]);
valuesString.setJSONObject(i, config2);
}
json = new JSONObject();
json.setJSONArray("Int", valuesInt);
json.setJSONArray("String", valuesString);
saveJSONObject(json, "data/config.json");
}
void loadConfig() {
int[] JsonIntValeur = { Mode, PortServeur, PortBuzzer1, PortBuzzer2, PortBuzzer3, PortBuzzer4, PortLive, PortMoniteur1, PortMoniteur2, DureePenalite};
String[] JsonStringValeur = { IpBuzzer1, IpBuzzer2, IpBuzzer3, IpBuzzer4, IpLive, IpMoniteur1, IpMoniteur2};
json = loadJSONObject("config.json");
for (int i = 0; i < JsonIntValeur.length; i++) {
JsonIntValeur[i] = json.getInt(JsonIntNom[i]);
}
}