mirror of
https://gitlab.com/wirelos/sprocket-lib.git
synced 2025-12-15 13:08:21 +01:00
81 lines
2.3 KiB
C
81 lines
2.3 KiB
C
#ifndef __JSON_STRUCT__
|
|
#define __JSON_STRUCT__
|
|
|
|
#include <ArduinoJson.h>
|
|
#include <FS.h>
|
|
#ifdef ESP32
|
|
#include "SPIFFS.h"
|
|
#endif
|
|
|
|
struct JsonStruct {
|
|
int valid = 0;
|
|
|
|
// ------------------------------------------------------------------------------------------
|
|
|
|
virtual void mapJsonObject(JsonObject& json);
|
|
virtual void fromJsonObject(JsonObject& json);
|
|
virtual int verifyJsonObject(JsonObject& json){
|
|
return json.success();
|
|
};
|
|
String toJsonString(){
|
|
DynamicJsonBuffer jsonBuffer(JSON_ARRAY_SIZE(300));
|
|
JsonObject& root = jsonBuffer.createObject();
|
|
mapJsonObject(root);
|
|
String jsonString;
|
|
root.printTo(jsonString);
|
|
return jsonString;
|
|
}
|
|
|
|
String getAttrFromJson(JsonObject& json, const char* attr, String defautValue = ""){
|
|
if(json.containsKey(String(attr))){
|
|
const char *value = json[attr];
|
|
return String(value);
|
|
}
|
|
return defautValue;
|
|
}
|
|
int getIntAttrFromJson(JsonObject& json, const char* attr, int defautValue = 0){
|
|
if(json.containsKey(attr)){
|
|
return json[attr];
|
|
}
|
|
return defautValue;
|
|
}
|
|
// Map a json object to this struct.
|
|
// Parse a json string and map parsed object
|
|
void fromJsonString(String& str){
|
|
DynamicJsonBuffer jsonBuffer(JSON_ARRAY_SIZE(300));
|
|
JsonObject& json = jsonBuffer.parseObject(str);
|
|
valid = verifyJsonObject(json);
|
|
if(valid) {
|
|
fromJsonObject(json);
|
|
}
|
|
};
|
|
|
|
void fromFile(const char* path) {
|
|
File configFile = SPIFFS.open(path, "r");
|
|
String cfgFileStr = configFile.readString();
|
|
DynamicJsonBuffer jsonBuffer;
|
|
JsonObject& json = jsonBuffer.parseObject(cfgFileStr);
|
|
|
|
valid = verifyJsonObject(json);
|
|
|
|
if(configFile) {
|
|
fromJsonObject(json);
|
|
}
|
|
if(!valid){
|
|
Serial.println("ERROR: read failed for " + String(path));
|
|
}
|
|
configFile.close();
|
|
}
|
|
void saveFile(const char* path) {
|
|
File configFile = SPIFFS.open(path, "w");
|
|
DynamicJsonBuffer jsonBuffer(JSON_ARRAY_SIZE(300));
|
|
JsonObject& json = jsonBuffer.createObject();
|
|
valid = configFile && verifyJsonObject(json);
|
|
if(valid){
|
|
mapJsonObject(json);
|
|
json.printTo(configFile);
|
|
}
|
|
}
|
|
};
|
|
|
|
#endif |