I'm trying to create a function that enters a key/value into a JSON file.
But, since value can be an int
or char
, I don't want to create 2 functions for each type.
Is there a way ?
void setValue(char *key, char* value){
StaticJsonDocument<512> tempJDOC;
tempJDOC[key]=value;
}
EDIT1
#ifndef myJSON_h
#define myJSON_h
#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"
class myJSON
{
private:
bool _useSerial=false;
char _filename[30];
public:
char *ver="myJSON_v1.1";
myJSON(char *filename, bool useserial=false);
bool file_exists();
bool file_remove();
bool format ();
bool FS_ok();
void saveJSON2file(JsonDocument& _doc);
void readJSON_file(JsonDocument& _doc);
void printJSON(JsonDocument& _doc);
void PrettyprintJSON(JsonDocument& _doc);
const char *getValue (char *key);
template <class T>
void setValue(const char *key, T value);
//void setValue(const char *key, char *value);
};
#endif
EDIT2
#ifndef myJSON_h
#define myJSON_h
#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"
#define LOG_LENGTH 4
#define DOC_SIZE 512
template <class T> // . <---- line added
class myJSON
{
private:
bool _useSerial=false;
char _filename[30];
public:
char *ver="myJSON_v1.1";
myJSON(char *filename, bool useserial=false);
bool file_exists();
bool file_remove();
bool format ();
bool FS_ok();
void saveJSON2file(JsonDocument& _doc);
void readJSON_file(JsonDocument& _doc);
void printJSON(JsonDocument& _doc);
void PrettyprintJSON(JsonDocument& _doc);
const char *getValue (const char *key);
void removeValue(const char *key);
// void setValue(const char *key, char *value); <--- comment out
void updateArray(char* array_key, int val);
void printFile();
void setValue(const char *key, T value); <---- Added
};
#endif
and in .cpp file :
void myJSON::setValue(const char *key, T value){
StaticJsonDocument<512> tempJDOC;
myJSON::readJSON_file(tempJDOC);
tempJDOC[key]=value;
myJSON::saveJSON2file(tempJDOC);
myJSON::PrettyprintJSON(tempJDOC);
}
char
parameter. The code seems to suggest that you are actually talking aboutchar *
parameter. So, what is it?char
orchar *
? These are two very different things. You have to edit your question and clarify that.template
- so I don't need to useint
norchar
int
orchar
you wouldn't need to do anything at all. You don't need any "templates". Just oneint
version of the function by itself would cover all cases, includingchar
, since in C and C++char
is just a small integer type. So, again, why are you asking this question? What is the problem withchar
that triggered it? Again, the code you provided implies that you needchar *
(or, better,const char *
). Notchar
, butconst char *
. You need to reflect it in your question, since currently neither the question not the accepted answer make sense.int
orconst char *
, albeit you are doing it implicitly. The compiler does it for you. But again, it is a matter ofint
andconst char *
, not a matter ofint
andchar
as you stated in your question.char
is completely irrelevant here.